【问题标题】:R dplyr - distinct accross all columnsR dplyr - 在所有列中不同
【发布时间】:2016-07-11 12:21:51
【问题描述】:

有没有办法指定 dplyr::distinct 应该使用所有列名而不诉诸非标准评估?

df <- data.frame(a=c(1,1,2),b=c(1,1,3))

df %>% distinct(a,b,.keep_all=FALSE)          # behavior I'd like to replicate

df %>% distinct(everything(),.keep_all=FALSE) # with syntax of this form

【问题讨论】:

  • df %&gt;% distinct()能给你想要的吗?
  • 不幸的是它没有。我相信传递数据框作为用于产生正确结果的唯一参数,但是最近的版本已经看到了 distinct 函数的变化。我目前得到:Error: No variables selected
  • df %&gt;% unique 作为替代方案,虽然不是最令人满意的答案。
  • 这是dplyr 中的新错误吗?我发誓我看到它工作正常。没有选择变量时出现相同的错误。
  • @Gopala,不是错误。只是新版本中的设计决定。我经常使用不带参数的 distinct() ,现在出于相同目的使用 unique()。

标签: r dplyr


【解决方案1】:

您可以使用下面的代码区分所有列。

library(dplyr)
library(data.table)

df <- data_frame(
  id = c(1, 1, 2, 2, 3, 3),
  value = c("a", "a", "b", "c", "d", "d")
)
# A tibble: 6 × 2
# id value
# <dbl> <chr>
# 1     1     a
# 2     1     a
# 3     2     b
# 4     2     c
# 5     3     d
# 6     3     d

# distinct with Non-Standard Evaluation
df %>% distinct()

# distinct with Standard Evaluation
df %>% distinct_()

# Also, you can set the column names with .dots.
df %>% distinct_(.dots = names(.))
# A tibble: 4 × 2
# id value
# <dbl> <chr>
# 1     1     a
# 2     2     b
# 3     2     c
# 4     3     d

# distinct with data.table
unique(as.data.table(df))
# id value
# 1:  1     a
# 2:  2     b
# 3:  2     c
# 4:  3     d

【讨论】:

    【解决方案2】:

    dplyr 的 1.0.5 版开始,以下两个选项产生相同的输出。

    df <- data.frame(a = c(1, 1, 2),
                     b = c(1, 1, 3))
    
    df %>% distinct(a, b)
    
      a b
    1 1 1
    2 2 3
    
    df %>% distinct(across(everything()))
    
      a b
    1 1 1
    2 2 3
    

    没有理由指定 .keep_all = FALSE 参数,因为这是默认值。

    您也可以使用tibble() 代替data.frame()

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 2022-08-17
      • 2012-06-21
      • 2018-08-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 2021-06-06
      相关资源
      最近更新 更多