r - Create variable/column equal to another column/factor frequency -


the short

i have

x <- data.frame(animal = c("ant", "cat", "dog", "ant", "dog", "ant", "ant")) 

and want create add column freq x such that

> x   animal freq 1    ant    4 2    cat    1 3    dog    2 4    ant    4 5    dog    2 6    ant    4 7    ant    4 

the long

i have

> x <- data.frame(animal = c("ant", "cat", "dog", "ant", "dog", "ant", "ant")) > x   animal 1    ant 2    cat 3    dog 4    ant 5    dog 6    ant 7    ant 

i know that

> table(x) x ant cat dog    4   1   2  

or

> count(x)   animal freq 1    ant    4 2    cat    1 3    dog    2 

and

> subset(count(x), animal == "ant")$freq [1] 4 

and that

> subset(count(x), animal == x[1,1])$freq [1] 4 > subset(count(x), animal == x[2,1])$freq [1] 1 

but i'm struggling put add column freq x such that

> x   animal freq 1    ant    4 2    cat    1 3    dog    2 4    ant    4 5    dog    2 6    ant    4 7    ant    4 

i suspect recommendation use apply in way can't function work properly. can following work

> fn.freq <- function(freqtable, variable){ +   return(subset(freqtable, animal == variable)$freq) + } > fn.freq(count(x),x[1,1]) [1]  

but still has animal hard coded function when want dynamic/a function variable attempts @ fail miserably.

any appreciated.

you can use ave:

x <- transform(x, freq = ave(as.integer(animal), animal, fun = length))  #   animal freq # 1    ant    4 # 2    cat    1 # 3    dog    2 # 4    ant    4 # 5    dog    2 # 6    ant    4 # 7    ant    4 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -