R dplyr 添加行总数

R Dplyr Add Rows Total

提问人:bvowe 提问时间:12/10/2022 最后编辑:bvowe 更新时间:12/11/2022 访问量:63

问:

    HAVE = data.frame(STUDENT = c(1,2,3,4),
YEAR = c(2020,2020,2021,2020),
                      SCORE1 = c(5,9,8,0),
                      TEST = c(7,11,3,9))
    
    WANT = data.frame(STUDENT = c(1,2,3,4, 'ALL'),
YEAR = c(2020, 2020, 2021, 2020,NA),
                      SCORE1 = c(5,9,8,0,22),
                       TEST = c(7,11,3,9,30))

我有“HAVE”并希望创建“WANT”,它可以这样做: 向 HAVE 添加行,其中 STUDENT = 'ALL' 和 SCORE1 = 求和 SCORE 的所有值,TEST = 求和 TEST 的所有值。

我尝试过这个但没有成功:

WANT = rowbind(HAVE, data.frame(STUDENT = 'ALL', SCORE1 = sum(HAVE$SCORE1), TEST = sum(HAVE$TEST))

但是有没有有效的DPLYR解决方案呢?

R dplyr 计数

评论


答:

4赞 TarJae 12/10/2022 #1

跟:dplyr

library(dplyr)

HAVE %>% 
  mutate(STUDENT = as.character(STUDENT)) %>% 
  bind_rows(summarise(.,
                      across(where(is.numeric), sum),
                      across(where(is.character), ~"All")))
  STUDENT SCORE1 TEST
1       1      5    7
2       2      9   11
3       3      8    3
4       4      0    9
5     All     22   30

也许有包装:janitor

libray(dplyr)
library(janitor)
HAVE %>% 
  adorn_totals("row") 
 STUDENT SCORE1 TEST
       1      5    7
       2      9   11
       3      8    3
       4      0    9
   Total     22   30

评论

0赞 bvowe 12/11/2022
这太完美了!假设还有其他一些列,并且您希望这些列的“总计”为空,您可以指定留空吗?就像如果有 YEAR 列,我们不想总结 YEAR...我们只是希望它是NA
1赞 bvowe 12/11/2022
例如,我更新了问题
1赞 TarJae 12/11/2022
在我的第一个解决方案中,dplyr 只需添加以下行:在这里,您可以指定要保留 NA 的所有列。希望清楚?!across(c(YEAR), ~ NA_real_))) %>% ...c()
3赞 chris jude 12/10/2022 #2

希望这有效!使用 rbind 或 bind_rows。

HAVE = data.frame(STUDENT = c(1,2,3,4),
                  SCORE1 = c(5,9,8,0),
                  TEST = c(7,11,3,9)) %>% 
  mutate(STUDENT = as.character(STUDENT))

WANT = bind_rows(HAVE, data.frame(STUDENT = 'ALL', SCORE1 = sum(HAVE$SCORE1),
                                  TEST = sum(HAVE$TEST)))


or

WANT <- rbind(HAVE, data.frame(STUDENT = 'ALL', SCORE1 = sum(HAVE$SCORE1), TEST = sum(HAVE$TEST))) 
4赞 akrun 12/11/2022 #3

或者与base Raddmargins

addmargins(as.matrix(HAVE[-(1:2)]), 1)