首页 > 解决方案 > 将多个列中的因子水平相加

问题描述

我有一个数据集,在多个列上重复了相同的四个因素。我正在尝试计算每列中的因子数(实际上是将行加在一起),但使用该summarise( n = n())命令没有任何成功。而不是得到一个不。列 x 4 大小的数据框,我只计算了整个内容。

这是我尝试过的代码:

percentages_20_notconstant <- allchangingreaders_20    %>% 
 
  group_by(resp) %>%
  summarise(resp = n(colnames(allchangingreaders_20))) 
structure(list(resp = structure(c(3L, 2L, 4L, 1L, 3L, 2L, 4L, 
1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L), .Label = c("Don't Know", 
"Leave", "Remain", "Will Not Vote"), class = "factor"), euRefVoteW1 = c(0L, 
0L, 0L, 0L, 3L, 5L, 1L, 0L, 12L, 0L, 0L, 1L, 17L, 10L, 0L, 5L, 
13L, 9L, 0L, 3L), euRefVoteW2 = c(0L, 0L, 0L, 0L, 4L, 5L, 0L, 
0L, 13L, 0L, 0L, 0L, 16L, 12L, 0L, 4L, 10L, 10L, 0L, 5L), euRefVoteW3 = c(0L, 
0L, 0L, 0L, 3L, 4L, 0L, 2L, 11L, 1L, 0L, 1L, 17L, 8L, 1L, 6L, 
13L, 8L, 0L, 4L), euRefVoteW4 = c(0L, 0L, 0L, 0L, 3L, 4L, 0L, 
2L, 12L, 0L, 0L, 1L, 19L, 10L, 0L, 3L, 12L, 8L, 0L, 5L), euRefVoteW6 = c(0L, 
0L, 0L, 0L, 4L, 4L, 0L, 1L, 13L, 0L, 0L, 0L, 20L, 8L, 0L, 4L, 
13L, 7L, 0L, 5L), euRefVoteW7 = c(0L, 0L, 0L, 0L, 2L, 6L, 0L, 
1L, 13L, 0L, 0L, 0L, 18L, 14L, 0L, 0L, 11L, 12L, 0L, 2L), euRefVoteW8 = c(0L, 
0L, 0L, 0L, 2L, 7L, 0L, 0L, 12L, 1L, 0L, 0L, 19L, 12L, 0L, 1L, 
12L, 12L, 0L, 1L), euRefVoteW9 = c(0L, 0L, 0L, 0L, 4L, 5L, 0L, 
0L, 12L, 1L, 0L, 0L, 21L, 11L, 0L, 0L, 11L, 14L, 0L, 0L)), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

通过更改单独的功能,我设法完成了我所追求的事情,但认为这项任务是有意义的。所以我想做的事情是从第一个 dput 到这个 dput:

structure(list(resp = structure(c(3L, 2L, 4L, 1L), .Label = c("Don't Know", 
"Leave", "Remain", "Will Not Vote"), class = "factor"), euRefVoteW1 = c(45L, 
24L, 1L, 9L), euRefVoteW2 = c(43L, 27L, 0L, 9L), euRefVoteW3 = c(44L, 
21L, 1L, 13L), euRefVoteW4 = c(46L, 22L, 0L, 11L), euRefVoteW6 = c(50L, 
19L, 0L, 10L), euRefVoteW7 = c(44L, 32L, 0L, 3L), euRefVoteW8 = c(45L, 
32L, 0L, 2L), euRefVoteW9 = c(48L, 31L, 0L, 0L), Paper = structure(c(1L, 
1L, 1L, 1L), .Label = "Former Readers", class = "factor")), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

这可以做到summarise吗?

标签: rtidyverse

解决方案


按'resp'分组后,获取rowSumscur_data()不包括分组列),然后用sum

library(dplyr)
allchangingreaders_20  %>% 
     group_by(resp) %>% 
     summarise(n = sum(rowSums(cur_data())), .groups = 'drop')

-输出

# A tibble: 4 x 2
#  resp              n
#* <fct>         <dbl>
#1 Don't Know       57
#2 Leave           208
#3 Remain          365
#4 Will Not Vote     2

或者如果它是大于 0 的元素的计数

allchangingreaders_20  %>% 
    group_by(resp) %>%
    summarise(n = sum(rowSums(cur_data() > 0)))
# A tibble: 4 x 2
#  resp              n
#* <fct>         <dbl>
#1 Don't Know       20
#2 Leave            27
#3 Remain           32
#4 Will Not Vote     2

更新

基于更新后的预期输出,我们还可以做

allchangingreaders_20  %>% 
     group_by(resp) %>% 
     summarise(across(where(is.numeric), sum), .groups = 'drop')

推荐阅读