Putting rowwise counts of value occurences into new variables, how to do that in R with dplyr?

后端 未结 3 1114
轻奢々
轻奢々 2020-12-20 06:55

I have a large dataframe (df) that looks like this:

structure(list(var1 = c(1, 2, 3, 4, 2, 3, 4, 3, 2), var2 = c(2, 
3, 4, 1, 2, 1, 1, 1, 3), var3 = c(4, 4,          


        
3条回答
  •  醉酒成梦
    2020-12-20 07:35

    This is a solution using base functions

    dd <- t(apply(df, 1, function(x) table(factor(x, levels=1:4))))
    colnames(dd) <- paste("n",1:4, sep="_")
    cbind(df, dd)
    

    Just use the table command across rows of your data.frame to get counts of each value from 1-4.

提交回复
热议问题