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

后端 未结 5 1706
-上瘾入骨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:47

    If you need to count any particular word/letter in the row.

    #Let df be a data frame with four variables (V1-V4)
                 df <- data.frame(V1=c(1,1,2,1,L),V2=c(1,L,2,2,L),
                 V3=c(1,2,2,1,L), V4=c(L, L, 1,2, L))
    

    For counting number of L in each row just use

    #This is how to compute a new variable counting occurences of "L" in V1-V4.      
    df$count.L <- apply(df, 1, function(x) length(which(x=="L")))
    

    The result will appear like this

    > df
      V1 V2 V3 V4 count.L
    1  1  1  1 L       1
    2  1  L  2 L       2
    3  2  2  2  1      0
    4  1  2  1  2      0
    

提交回复
热议问题