将一个coloum的每个唯一值求和为其他coloum R中的每个唯一值

时间:2018-10-12 18:51:14

标签: r dataframe unique subset subset-sum

我的数据框示例:

df<- structure(list(Var1 = c("A-01", "A-01", "A-02", "A-01", "A-02", 
                         "A-03", "A-01", "A-02", "A-03", "A-04", "A-01", "A-02", "A-03", 
                         "A-04", "A-05", "A-01", "A-02", "A-03", "A-04", "A-05", "A-07", 
                         "A-01", "A-02", "A-03", "A-04", "A-05", "A-07", "A-08", "A-01", 
                         "A-02"), Var2 = c("A-02", "A-03", "A-03", "A-04", "A-04", "A-04", 
                                           "A-05", "A-05", "A-05", "A-05", "A-07", "A-07", "A-07", "A-07", 
                                           "A-07", "A-08", "A-08", "A-08", "A-08", "A-08", "A-08", "A-09", 
                                           "A-09", "A-09", "A-09", "A-09", "A-09", "A-09", "A-11", "A-11"
                         ), value.data = c(1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 
                                           -1, -1, 1, NA, -1, 1, 1, -1, -1, -1, 1, -1, 0, 1, -1, 1, 1)), row.names = c(37L, 
                                                                                                                       73L, 74L, 109L, 110L, 111L, 145L, 146L, 147L, 148L, 181L, 182L, 
                                                                                                                       183L, 184L, 185L, 217L, 218L, 219L, 220L, 221L, 222L, 253L, 254L, 
                                                                                                                       255L, 256L, 257L, 258L, 259L, 289L, 290L), class = "data.frame")

因此,每次在“ Var1”或“ Var2”中出现变量时,都会对“ value.data”中不同唯一值的出现次数进行计数。

所以我将有如下的汇总表:

df_sum<- data.frame(Var = c(rep("A-01", 4), rep("A-02", 4)), value.data = c(rep(c(1, -1, 0, NA), 2)), sum=c(5,3,0,0,4,3,0,1))

我可以一个子集一个地做。对于数百个变量而言效率不高。

谢谢

1 个答案:

答案 0 :(得分:2)

如果您将数据转换为长格式,则可以使用count

library(tidyverse)

df %>% 
  melt('value.data') %>% 
  count(value, value.data) %>% 
  complete(value, value.data, fill = list(n = 0)) %>% 
  mutate_if(is.numeric, as.integer)

# # A tibble: 36 x 3
#    value value.data     n
#    <chr>      <int> <int>
#  1 A-01         - 1     3
#  2 A-01           0     0
#  3 A-01           1     5
#  4 A-01          NA     0
#  5 A-02         - 1     3
#  6 A-02           0     0
#  7 A-02           1     4
#  8 A-02          NA     1
#  9 A-03         - 1     5
# 10 A-03           0     0
# # ... with 26 more rows