【问题标题】:R- create a superset from two vectors?R-从两个向量创建一个超集?
【发布时间】:2020-06-27 17:00:51
【问题描述】:

我正在尝试添加一个向量,它是 R 中其他两个列表的“超集”。现在,我认为我没有正确创建列表,但希望这可以为您提供一个示例我正在尝试做:

mygroups<-data.frame(number=c(1:5),members=c("a,b,c,d","e,f","b,c,d","e,f,g","c,d,a"))
mygroups2<- merge(mygroups, mygroups, by=NULL) %>% 
  filter(number.x!=number.y) %>%
  mutate(setofall = paste(members.x,members.y, sep=","))
mygroups2

现在,“setofall”并不完全是“members”的超集——它是一个直接的串联。例如,“setofall”对于“a,b​​,c,d”和“b,c,d”被列为“a,b,c,d,b,c,d”,但“superset”应该只是"a,b,c,d" 表示这两个。

我已经搜索并发现了有关checking 一个向量是否是另一个向量的超集的问题,而不是关于查找超集本身的问题。

【问题讨论】:

    标签: r set


    【解决方案1】:

    这是一个使用更多 tidyverse 的选项,您的 superset 通常称为 union

    library(dplyr)
    library(purrr)
    
    mygroups<-data.frame(number=c(1:5),members=c("a,b,c,d","e,f","b,c,d","e,f,g","c,d,a"))
    
    mygroups2<- merge(mygroups, mygroups, by=NULL) %>%
       filter(number.x!=number.y)  %>%
       mutate(members.x = strsplit(members.x, ","),
              members.y = strsplit(members.y, ","))
    mygroups2$setofall <- purrr::map2(mygroups2$members.x, mygroups2$members.y, ~ union(.x, .y))
    
    mygroups2
    #>    number.x  members.x number.y  members.y            setofall
    #> 1         2       e, f        1 a, b, c, d    e, f, a, b, c, d
    #> 2         3    b, c, d        1 a, b, c, d          b, c, d, a
    #> 3         4    e, f, g        1 a, b, c, d e, f, g, a, b, c, d
    #> 4         5    c, d, a        1 a, b, c, d          c, d, a, b
    #> 5         1 a, b, c, d        2       e, f    a, b, c, d, e, f
    #> 6         3    b, c, d        2       e, f       b, c, d, e, f
    #> 7         4    e, f, g        2       e, f             e, f, g
    #> 8         5    c, d, a        2       e, f       c, d, a, e, f
    #> 9         1 a, b, c, d        3    b, c, d          a, b, c, d
    #> 10        2       e, f        3    b, c, d       e, f, b, c, d
    #> 11        4    e, f, g        3    b, c, d    e, f, g, b, c, d
    #> 12        5    c, d, a        3    b, c, d          c, d, a, b
    #> 13        1 a, b, c, d        4    e, f, g a, b, c, d, e, f, g
    #> 14        2       e, f        4    e, f, g             e, f, g
    #> 15        3    b, c, d        4    e, f, g    b, c, d, e, f, g
    #> 16        5    c, d, a        4    e, f, g    c, d, a, e, f, g
    #> 17        1 a, b, c, d        5    c, d, a          a, b, c, d
    #> 18        2       e, f        5    c, d, a       e, f, c, d, a
    #> 19        3    b, c, d        5    c, d, a          b, c, d, a
    #> 20        4    e, f, g        5    c, d, a    e, f, g, c, d, a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2022-01-20
      • 2020-11-26
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      相关资源
      最近更新 更多