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

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

    I think that there ought to be a simpler way to do this, but the best way that I can think of to get a table of counts is to loop (implicitly using sapply) over the unique values in the dataframe.

    #Some example data
    df <- data.frame(a=c(1,1,2,2,3,9),b=c(1,2,3,2,3,1))
    df
    #  a b
    #1 1 1
    #2 1 2
    #3 2 3
    #4 2 2
    #5 3 3
    #6 9 1
    
    levels=unique(do.call(c,df)) #all unique values in df
    out <- sapply(levels,function(x)rowSums(df==x)) #count occurrences of x in each row
    colnames(out) <- levels
    out
    #     1 2 3 9
    #[1,] 2 0 0 0
    #[2,] 1 1 0 0
    #[3,] 0 1 1 0
    #[4,] 0 2 0 0
    #[5,] 0 0 2 0
    #[6,] 1 0 0 1
    

提交回复
热议问题