Count number of values in row using dplyr

前端 未结 5 920
梦如初夏
梦如初夏 2020-12-19 13:07

This question should have a simple, elegant solution but I can\'t figure it out, so here it goes:

Let\'s say I have the following dataset and I want to count the num

5条回答
  •  时光取名叫无心
    2020-12-19 13:53

    One approach is to use a combination of dplyr and tidyr to convert data into long format, and do the computation:

    library(dplyr)
    library(tidyr)
    df %>%
      gather(key, value, -ID) %>%
      group_by(ID) %>%
      summarise(numtwos = sum(value == 2)) %>%
      inner_join(df, .)
    

    Output is as follows:

      ID X1 X2 X3 numtwos
    1  A  2  5  2       2
    2  B  2  5  1       1
    3  C  3  4  4       0
    4  D  5  4  2       1
    5  E  2  1  4       1
    

提交回复
热议问题