【问题标题】:Finding Number of Groups that Contain Specific Pairs in Data Frame在数据框中查找包含特定对的组数
【发布时间】:2015-12-29 16:21:52
【问题描述】:

我正在尝试查找包含特定对的数据框中的组数。这是我所做的和所需输出的示例。

创建数据

df=data.frame(c("Sam","Sam","Sam","Jason", "Jason", "Kelly", "Kelly"),
c("e","f","g","h", "h", "e", "f"))

names(df)=c('name','value')

对查看至少没有出现在一个特定名称中的配对不感兴趣,因此我在生成配对之前放弃了这些观察

df=df[!duplicated(df[1:2]),]

df=df[ave(rep(1, nrow(df)), df$name, FUN=length)>1,]

pairs=t(combn(unique(df$value), 2))

现在我有两个像这样的对象

   name value
1   Sam     e
2   Sam     f
3   Sam     g
6 Kelly     e
7 Kelly     f

     [,1] [,2]
[1,] e    f   
[2,] e    g   
[3,] f    g  

我想要的输出

   pair.1    pair.2  occurrences
1   e          f         2
2   e          g         1
3   f          g         1

【问题讨论】:

  • 查看igraph 包。我相信你可以在这里找到一些骗子。并且请不要嵌入到您的 MWE 生产线中,这会与您的环境相混淆。
  • This post 应该有助于开始;并添加 merge: merge(data.frame(val1 = pairs[, 1L], val2 = pairs[, 2L]), setNames(as.data.frame(as.table(crossprod(table(df)))), c("val1", "val2", "freq")))

标签: r


【解决方案1】:

我们merge数据集本身按'name',sort'value'列按'row',将数据集转换为data.table,删除具有相同'value'元素的行,按分组'value' 列,获取 nrow (.N) 并除以 2。

d1 <- merge(df, df, by.x='name', by.y='name')
d1[-1] <- t(apply(d1[-1], 1, sort))
library(data.table)
setDT(d1)[value.x!=value.y][,.N/2 ,.(value.x, value.y)]
#   value.x value.y V1
#1:       e       f  2
#2:       e       g  1
#3:       f       g  1

或者使用与@jeremycg 的帖子中类似的方法

 setDT(df)[df, on='name', allow.cartesian=TRUE
     ][as.character(value)< as.character(i.value), .N, .(value, i.value)]

【讨论】:

    【解决方案2】:

    这是使用dplyr 的答案。请参阅内联的 cmets 以获得解释:

    library(dplyr) #load dplyr
    df %>% #your data
     left_join(df, by = "name") %>% #merge against your own data
     filter(as.character(value.x) < as.character(value.y)) %>% #filter out any where the two are equal, and make sure we only have one of each pair
     group_by(value.x, value.y) %>% #group by the two vars
     summarise(n()) #count them
    
    Source: local data frame [3 x 3]
    Groups: value.x [?]
    
      value.x value.y   n()
       (fctr)  (fctr) (int)
    1       e       f     2
    2       e       g     1
    3       f       g     1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 2014-12-16
      • 2020-11-13
      • 2020-04-19
      • 2017-05-12
      • 1970-01-01
      相关资源
      最近更新 更多