简体   繁体   中英

Sum across multiple columns

I imagine this is pretty basic question, but I am kind of lost. I have three variables: A, B and C, that range from 0-4. I would like to take a total count of those that equal 1 and create a new variable with the total sum. For example, if variables A and B equal 1, the new variable SumABC would equal 2. I've attempted doing this with mutate, but I know there has got to be an easier way.

x <- mutate(z,
 SumABC = 
  ifelse(A == 1, 1, 
  ifelse(B ==1, 1, 
  ifelse(C ==1, 1, 
  ifelse(A ==1 & B ==1, 2,
  ifelse(A ==1 & C ==1, 2,
  ifelse(B ==1 & C ==1, 2,
  ifelse(A ==1 & B ==1 & C == 1, 3, 0))))))))

Maybe not the most sophisticated, but it works:

df <- data.frame(A=sample(0:4,10,replace = T),B=sample(0:4,10,replace = T),C=sample(0:4,10,replace = T))

df$EQ1 <- rowSums(df == 1)

# Output

df

   A B C EQ1
1  2 3 3   0
2  1 4 4   1
3  1 3 4   1
4  2 4 3   0
5  1 4 1   2
6  1 3 1   2
7  1 2 2   1
8  1 4 4   1
9  2 4 4   0
10 2 3 4   0

Edit:

Or if you prefer with vectors (of same size):

vecs <- sapply(c('A','B','C'),function(x) sample(0:4,10,replace = T),simplify = F)

tsum <- (vecs$A == 1)*1 + (vecs$B == 1)*1 + (vecs$C == 1)*1

# output

> tsum
 [1] 0 0 1 0 0 0 0 1 0 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM