如何计算R中将一项与另一项分组在一起的次数?

时间:2018-07-06 08:31:37

标签: r dplyr

我有一张桌子(示例):

 Group  |  Country
-------------------
 Group1      SE
 Group1      DE  
 Group2      SE   
 Group2      DE
 Group2      FI
 Group3      SE
 Group3      FI

我正在尝试将其转换为:

 Country 1 | Country 2 | Count
-------------------------------
    SE          DE         2
    SE          FI         2
    FI          DE         1

我尝试使用dplyr的计数group_by进行汇总,但是我似乎无法理解。相反,我得到了一个表格,其中每个国家/地区为列,每个国家/地区为行,并且如果该国家/地区属于该国家/地区,则该单元格中的值为1或0。

3 个答案:

答案 0 :(得分:3)

我们可以使用base R方法,使用table获取频率,进行crossprod,将对角线和下三角元素设置为NA并删除{{转换为NA

后的1}}行
data.frame

数据

m1 <- crossprod(table(df1))
m1[lower.tri(m1, diag = TRUE)] <- NA
subset(as.data.frame.table(m1), !is.na(Freq))
#    Country Country.1 Freq
#4      DE        FI    1
#7      DE        SE    2
#8      FI        SE    2

答案 1 :(得分:1)

这是使用tidyverse的另一种combn方法

library(tidyverse)
df %>%
    group_by(Group) %>%
    summarise(cmbn = list(apply(combn(Country, 2), 2, function(x)
        paste(sort(x), collapse = "_")))) %>%
    unnest() %>%
    select(-Group) %>%
    separate(cmbn, into = c("Country 1", "Country 2"), sep = "_") %>%
    count(`Country 1`, `Country 2`)
## A tibble: 3 x 3
#  `Country 1` `Country 2`     n
#  <chr>       <chr>       <int>
#1 DE          FI              1
#2 DE          SE              2
#3 FI          SE              2

样本数据

df <- read.table(text =
    "Group    Country
 Group1      SE
 Group1      DE
 Group2      SE
 Group2      DE
 Group2      FI
 Group3      SE
 Group3      FI", header = T, stringsAsFactors = F)

答案 2 :(得分:1)

另一种dplyr方法将一种功能应用于每个Country值组合

df = read.table(text = "
Group Country
Group1      SE
Group1      DE  
Group2      SE   
Group2      DE
Group2      FI
Group3      SE
Group3      FI
", header=T, stringsAsFactors=F)

library(dplyr)

# function that takes 2 Country values and returns the number of common groups they have
f = function(x,y) { 
  df %>% 
    filter(Country %in% c(x,y)) %>% 
    distinct() %>%
    count(Group) %>%
    filter(n > 1) %>%
    nrow() 
}

# vectorising the function
f = Vectorize(f)

# applying the function to each Country value combination
data.frame(t(combn(unique(df$Country), 2)), stringsAsFactors = F) %>%
  mutate(NumGroups = f(X1, X2))

#   X1 X2 NumGroups
# 1 SE DE         2
# 2 SE FI         2
# 3 DE FI         1