问题描述
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)
。