Finding the number of unique variables per factor in R -


i have dataframe looks this:

id <- c(1,2,3,4,5,6,7,8,9,10) val <- c("a", "b", "c", "a", "b", "a", "c", "a", "a", "c") df <- data.frame(id,val) 

i trying create vector of length 10 which, every id, gives number of rows in df same value val. output should be

out <- c(5, 2, 3, 5, 2, 5, 3, 5, 5, 3) 

it's opposite of

with(df, tapply(val, id, function(x) length(unique(x)))) 

if makes sense? maybe merge with(df, tapply(id, val, function(x) length(unique(x)))) df somehow, seems ugly solution.

the ave function meant tasks such this

cc<-with(df, ave(id,val, fun=length)) cbind(df, cc) 

will result in

id val cc 1   1    5 2   2   b  2 3   3   c  3 4   4    5 5   5   b  2 6   6    5 7   7   c  3 8   8    5 9   9    5 10 10   c  3 

Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -