如何解决管道行汇总的简单方法
dput(sample)
structure(list(VR1 = c(NA,NA,1L,0L,NA),VR2 = c(NA,VR3 = c(NA,VR4 = c(NA,VR5 = c(NA,VR6 =
c(NA,VR7 = c(NA,VR8 =
c(NA,VR9 = c(NA,VR10 =
c(NA,VR11 = c(NA,VR12 =
c(NA,VR13 = c(NA,VR14 =
c(NA,VR15 = c(NA,VR16 =
c(NA,VR17 = c(NA,VR18 =
c(NA,VR19 = c(NA,VR20 =
c(NA,NA)),row.names = c(NA,6L),class =
"data.frame")
我正在做很多先前的操作(例如删除列),但是我没有找到将简单的rowums传递到新列的函数。这是我一直在尝试的
sample <- sample %>% mutate(total = rowSums(1:20))
我一直在互联网上寻找
sum(c_across
但是R不能识别它,尽管加载了tidyverse和dplyr
解决方法
dplyr
选项会c_across()
,但需要一个行ID:
library(dplyr)
#Code
sample %>% mutate(id=1:n())%>%
rowwise(id) %>%
mutate(total=sum(c_across(VR1:VR20),na.rm=T))
输出:
# A tibble: 6 x 22
# Rowwise: id
VR1 VR2 VR3 VR4 VR5 VR6 VR7 VR8 VR9 VR10 VR11 VR12 VR13 VR14 VR15 VR16
<int> <lgl> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
2 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
3 1 NA 0 1 1 0 1 0 1 1 0 0 1 1 1 0
4 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
5 0 NA 0 0 1 0 0 0 1 0 0 0 0 0 1 0
6 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
# ... with 6 more variables: VR17 <int>,VR18 <int>,VR19 <int>,VR20 <int>,id <int>,total <int>
使用的数据是您共享的dput(sample)
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。