Count number of values in row using dplyr

前端 未结 5 923
梦如初夏
梦如初夏 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 14:08

    Just wanted to add to the answer of @evan.oman in case you only want to sum rows for specific columns, not all of them. You can use the regular select and/or select_helpers functions. In this example, we don't want to include X1 in rowSums:

    df %>% 
      mutate(numtwos = rowSums(select(., -X1) == 2))
    
      ID X1 X2 X3 numtwos
    1  A  2  5  2       1
    2  B  2  5  1       0
    3  C  3  4  4       0
    4  D  5  4  2       1
    5  E  2  1  4       0
    

提交回复
热议问题