您如何根据所需的一组变量/列求和不同列的二进制变量?

问题描述 投票:0回答:1

我在下面的代码中使用了总共​​25个变量,它正常工作。它显示为1或0:

jb$finances <- ifelse(grepl("Finances", jb$content.roll),1,0)

我希望能够将我刚刚(使用上面的代码)创建的所选列/变量的倍数中的每一行中的“ 1”个数添加到另一列“ sum.content”中。我用下面的代码:

jb <- jb %>%
mutate(sum.content=sum(jb$Finances,jb$Exercise,jb$Volunteer,jb$Relationships,jb$Laugh,jb$Gratitude,jb$Regrets,jb$Meditate,jb$Clutter))

使用上面的代码我没有得到错误,但是我没有得到想要的结果。

此行的结果是我所有行中的14。我期望<9,因为我只选择了9个变量。我不想删除其他变量,例如V1和V2,我只想着重于求和变量。

这是我使用代码得到的:

    V1  V2... Finances Exercise Volunteer Relationships Laugh sum.content
1               1        1        1          1            0    14
2               0        1        0          0            1    14
2               0        0        0          0            1    14

这就是我想要的:

    V1  V2... Finances Exercise Volunteer Relationships Laugh sum.content
1               1        1        1          1            0       4
2               0        1        0          0            1       1
2               0        0        0          0            1       1

我希望R在每行(我要选择的列内)添加1的数目。我要如何将1的加法合并到代码中(来自一组变量/列)?

r
1个回答
0
投票

这里是一个答案,它使用dplyr对以字母V开头的变量行进行求和。我们将模拟一些数据,转换为二进制,然后对行求和。

data <- matrix(rnorm(100,100,30),nrow = 10)
# recode to binary
data <- apply(data,2,function(x){x <- ifelse(x > 100,1,0)})
# change some of the column names to illustrate impact of
# select() within mutate()
colnames(data) <- c(paste0("V",1:5),paste0("X",1:5))

as.data.frame(data) %>% 
     mutate(total = select(.,starts_with("V")) %>% rowSums)

...和输出,总和应等于V1-V5的总和,但不等于X1-X5:

   V1 V2 V3 V4 V5 X1 X2 X3 X4 X5 total
1   1  0  0  0  1  0  0  0  1  0     2
2   1  0  0  1  0  0  0  1  1  0     2
3   1  1  1  0  1  0  0  0  1  0     4
4   0  0  1  1  0  1  0  0  1  0     2
5   0  0  1  0  1  0  1  1  1  0     2
6   0  1  1  0  1  0  0  1  1  1     3
7   1  0  1  1  0  0  0  0  0  1     3
8   1  0  0  1  1  1  0  1  1  1     3
9   1  1  0  0  1  0  1  1  0  0     3
10  0  1  1  0  1  1  0  0  1  0     3
>
© www.soinside.com 2019 - 2024. All rights reserved.