Count number of values in row using dplyr

前端 未结 5 925
梦如初夏
梦如初夏 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:06

    You can use do, which doesn't add the column to your original data frame and you need to add the column to your original data frame.

    df %>%
        rowwise %>%
        do(numtwos = sum(.[-1] == 2)) %>% 
        data.frame
      numtwos
    1       2
    2       1
    3       0
    4       1
    5       1
    

    Add a cbind to bind the new column to the original data frame:

    df %>%
         rowwise %>%
         do(numtwos = sum(.[-1] == 2)) %>% 
         data.frame %>% cbind(df, .)
    
      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 
    

提交回复
热议问题