计算 R 中每组 table 的频率

count frequencies across a table per group in R

我有一个数据 table df,我想按第一列 'location' 对它进行分组, 并计算所有 table 的条目频率,包括列和行:

df

location   NN_1    NN_2   NN_3
    NYC    17      17      17
    NYC    17      16      1
    LA     1        1      10
    LA     16      10      1

可以通过以下方式获得:

df <- structure(list(location = c("NYC", "NYC", "LA", "LA"), 
                     NN_1 = c(17, 17, 1, 16), 
                     NN_2 = c(17, 16, 1, 10), 
                     NN_3 = c(17, 1, 10, 1)),
                     class = "data.frame", 
                     row.names = c(NA, -4L))

我想计算 17 在给定位置重复了多少次,例如 NYC:

output
location   NNs  freq
    NYC    17      4
    NYC    16      1
    NYC     1      1
    LA      1      3
    LA      16     1
    LA      10     2

可能的 tidyverse 解决方案:

df %>% 
  gather("key", "NNs", 2:ncol(.)) %>% 
  group_by(location, NNs) %>% 
  summarize(freq = n()) %>% 
  arrange(desc(location), desc(NNs))

Base R 解决方案,有效地做与 tidyverse 解决方案相同的事情。将第一个 location 列标识符放在所有其他列上,然后制表:

as.data.frame(table(cbind(df[1], NNs=unlist(df[-1]))))
#  location NNs Freq
#1       LA   1    3
#2      NYC   1    1
#3       LA  10    2
#4      NYC  10    0
#5       LA  16    1
#6      NYC  16    1
#7       LA  17    0
#8      NYC  17    4