Search code examples
rdataframerecode

How to count the number of occurrences of a given value for each row?


I'm sure this is a really easy fix but I can't seem to find the answer... I am trying to create a column at the end of my dataframe that is a sum of the number of times a specific value (say "1") appears across that row. So for example, if I started with the following dataframe:

X1 <- c(5,1,7,8,1,5)
X2 <- c(5,0,0,2,3,7)
X3 <- c(6,2,3,4,1,7)
X4 <- c(1,1,5,2,1,7)

df <- data.frame(id,X1,X2,X3,X4)

  id X1 X2 X3 X4
1  1  5  5  6  1
2  2  1  0  1  1
3  3  7  0  3  5
4  4  8  2  4  2
5  5  1  3  2  1
6  6  5  7  7  7

and I was trying to identify how many times the value "1" appears across that row, I would want the output to look like this:

  id X1 X2 X3 X4 one_appears
1  1  5  5  6  1           2
2  2  1  0  1  1           3
3  3  7  0  3  5           0
4  4  8  2  4  2           0
5  5  1  3  2  1           2
6  6  5  7  7  7           0

Thanks very much in advance!


Solution

  • We can use rowSums on a logical matrix

    df$one_appears <- rowSums(df == 1, na.rm = TRUE)
    

    -output

    > df
      id X1 X2 X3 X4 one_appears
    1  1  5  5  6  1           2
    2  2  1  0  1  1           3
    3  3  7  0  3  5           0
    4  4  8  2  4  2           0
    5  5  1  3  2  1           2
    6  6  5  7  7  7           0