【问题标题】:Unique combinations of two variables in R (dplyr::distinct not working) [duplicate]R中两个变量的唯一组合(dplyr::distinct不起作用)[重复]
【发布时间】:2019-12-05 20:08:50
【问题描述】:

我希望从数据框的两列中过滤字符串的唯一组合。

初始数据帧:

trial<-data.frame(x=c("A","B"),y=c("B","A"))
trial
  x y
1 A B
2 B A

想要的结果:

  x y
1 A B

到目前为止,我尝试使用dplyr::distinct() version 0.8.3unique(trial[,c("x","y"]),但都没有产生预期的结果。向每列添加更多字符以手动创建组合并没有帮助。

        trial %>% 
      distinct(x,y)
      x y
    1 A B
    2 B A

    unique(trial[,c("x","y")])
      x y
    1 A B
    2 B A

为了使这些功能起作用,我是否缺少某些东西?

【问题讨论】:

    标签: r dataframe dplyr combinations tidyverse


    【解决方案1】:

    我们可以对行中的值重新排序,然后使用distinct

    library(dplyr)
    trial %>% 
      mutate_all(as.character) %>%
      transmute(x1 = pmin(x, y), y1 = pmax(x, y)) %>%
      rename_all(~ names(trial)) %>%
      distinct
     #  x y
     #1 A B
    

    或在base R

    unique(t(apply(trial, 1, sort)))
    #    [,1] [,2]
    #[1,] "A"  "B" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2020-11-13
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      相关资源
      最近更新 更多