如何解决使用 tidyverse 汇总对多列应用相同的操作 数据
我正在尝试创建一个汇总表,其中给出了按年份排序的 17 个问题的回答比例。我只是不知道如何在没有硬编码的情况下轻松地将汇总操作应用于多列。
不幸的是,我无法使用summary_at 或summary_all 函数,因为我正在使用数据框。我正在考虑编写一个函数,循环遍历列,并将汇总列绑定在一起,但汇总列名有点奇怪,不能是字符类型。你有什么推荐?
这是我目前拥有的:
s2 <- db %>%
group_by(Year)%>%
summarize(Q1=round(sum(Q1d,na.rm=TRUE)*100/length(which(!is.na(Q1d))),1),Q2=round(sum(Q2d,na.rm=TRUE)*100/length(which(!is.na(Q2d))),Q3=round(sum(Q3d,na.rm=TRUE)*100/length(which(!is.na(Q3d))),Q4=round(sum(Q4d,na.rm=TRUE)*100/length(which(!is.na(Q4d))),Q5=round(sum(Q5d,na.rm=TRUE)*100/length(which(!is.na(Q5d))),Q6=round(sum(Q6d,na.rm=TRUE)*100/length(which(!is.na(Q6d))),Q7=round(sum(Q7d,na.rm=TRUE)*100/length(which(!is.na(Q7d))),Q8=round(sum(Q8d,na.rm=TRUE)*100/length(which(!is.na(Q8d))),Q9=round(sum(Q9d,na.rm=TRUE)*100/length(which(!is.na(Q9d))),Q10=round(sum(Q10d,na.rm=TRUE)*100/length(which(!is.na(Q10d))),Q11=round(sum(Q11d,na.rm=TRUE)*100/length(which(!is.na(Q11d))),Q12=round(sum(Q12d,na.rm=TRUE)*100/length(which(!is.na(Q12d))),Q13=round(sum(Q13d,na.rm=TRUE)*100/length(which(!is.na(Q13d))),Q14=round(sum(Q14d,na.rm=TRUE)*100/length(which(!is.na(Q14d))),Q15=round(sum(Q15d,na.rm=TRUE)*100/length(which(!is.na(Q15d))),Q16=round(sum(Q16d,na.rm=TRUE)*100/length(which(!is.na(Q16d))),Q17=round(sum(Q17d,na.rm=TRUE)*100/length(which(!is.na(Q17d))),)
注意:Q1d、Q2d...是列的名称
解决方法
我们可以在across
中使用dplyr
library(dplyr)
library(stringr)
db %>%
group_by(Year) %>%
summarise(across(matches('^Q\\d+d$'),~
sum(.,na.rm = TRUE) * 100 /sum(!is.na(.))),.groups = 'drop') %>%
rename_with(~ str_remove(.,'d$'),-Year)
或使用 collapse
library(collapse)
f1 <- function(x) sum(x,na.rm = TRUE) * 100/sum(!is.na(x))
collap(db,~ Year,FUN = f1)
# Year Q1d Q2d
#1 2010 250.0000 350
#2 2015 293.3333 320
数据
db <- data.frame(Year = c(2010,2010,2015,2015),Q1d = c(2.5,NA,3,3.5,2.3),Q2d = c(NA,2,4.6,3))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。