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,
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.
table
data.frame