如何通过仅指定要排除的列来保留数据帧中除某些列以外的所有不同行。在下面的示例中

library(dplyr)
dat <- data_frame(
    x = c("a", "a", "b"),
    y = c("c", "c", "d"),
    z = c("e", "f", "f")
)

我想通过仅指定我想排除列x来返回一个数据帧,其中包含变量yz中的所有不同行。返回的数据帧应看起来像是从此处返回的数据帧
dat %>% distinct(x, y)

您可能会认为您可以执行以下操作,但会导致错误
dat %>% distinct(-z)

我更喜欢tidyverse解决方案

最佳答案

做就是了:

library(dplyr)

dat %>%
  distinct_at(vars(-z))
输出:
# A tibble: 2 x 2
  x     y
  <chr> <chr>
1 a     c
2 b     d
dplyr 1.0.0开始,您可以使用across:
dat %>%
  distinct(across(-z))

关于r - 在保留所有不同的行时如何指定要排除的列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54771651/

10-12 17:52
查看更多