Count occurrences of value in a set of variables in R (per row)

后端 未结 5 1751
-上瘾入骨i
-上瘾入骨i 2021-01-06 01:16

Let\'s say I have a data frame with 10 numeric variables V1-V10 (columns) and multiple rows (cases).

What I would like R to do is: For each case, give me the number

5条回答
  •  情深已故
    2021-01-06 01:27

    In my effort to find something similar to Count from SPSS in R is as follows:

    `df <- data.frame(a=c(1,1,NA,2,3,9),b=c(1,2,3,2,NA,1))` #Dummy data with NAs 
    
    `df %>% 
      dplyr::mutate(count = rowSums( #this allows calculate sum across rows
        dplyr::select(., #Slicing on .  
                      dplyr::one_of( #within select use one_of by clarifying which columns your want
                        c('a','b'))), na.rm = T)) #once the columns are specified, that's all you need, na.rm is cherry on top
    

    That's how the output looks like

    > df a b count 1 1 1 2 2 1 2 3 3 NA 3 3 4 2 2 4 5 3 NA 3 6 9 1 10

    Hope it helps :-)

提交回复
热议问题