Search code examples
rdataframe

How to tally occurrences of same value across columns in R?


I have a dataframe like so:

exit x1 x2 x3 x4
3 4 6 6 NA
4 4 6 6 NA
5 4 6 6 NA
6 4 6 6 NA

I am only interested when exit = xi, where i = 1, 2, 3, 4 as shown in the data. I want to count the number of times exit = xi. So, the ideal output I am looking for is:

exit x1 x2 x3 x4 n
3 4 6 6 NA 0
4 4 6 6 NA 1
5 4 6 6 NA 0
6 4 6 6 NA 2

Ideally I would like to be using ifelse() in R, but it seems I am unable to figure out a good logical path.


Solution

  • A base solution:

    df$n = rowSums(apply(df, 2, function(col) col == df$exit)[, -1], na.rm = T)
    
    > df
      exit x1 x2 x3 x4 n
    1    3  4  6  6 NA 0
    2    4  4  6  6 NA 1
    3    5  4  6  6 NA 0
    4    6  4  6  6 NA 2
    

    Data:

    > dput(df)
    structure(list(exit = 3:6, x1 = c(4L, 4L, 4L, 4L), x2 = c(6L, 
    6L, 6L, 6L), x3 = c(6L, 6L, 6L, 6L), x4 = c(NA, NA, NA, NA), 
        n = c(0, 1, 0, 2)), row.names = c(NA, -4L), class = "data.frame")