0

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))))))))
user7777508
  • 101
  • 1
  • 3
  • 9
  • 1
    It's easier to help if you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data and desired output so that possible solutions can be tested. – MrFlick May 04 '17 at 18:23
  • 7
    probably something like `rowSums(z[c("A","B","C")] == 1)` for a data.frame named z. – lmo May 04 '17 at 18:23

1 Answers1

1

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
Val
  • 6,585
  • 5
  • 22
  • 52