[R] For loop for frequency counting

arun smartpink111 at yahoo.com
Thu Jan 2 20:11:39 CET 2014


Hi,

May be this helps:
var1 <- ave(seq_along(fam),fam,FUN=length)
 names(var1) <- fam
 var1
#2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 
#4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 


#or
table(fam)[as.character(fam)]
#fam
#2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 
#4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 


fam1 <- c(fam,2)

 var2 <- table(fam1)[as.character(fam1)]
 names(dimnames(var2)) <- NULL
 var2
#2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 2 
#5 5 5 5 4 4 4 4 4 4 4 4 4 4 4 4 5 

A.K.




fam <- sort(rep(2:5, 4)) 

I want to create a new variable of the same length as fam, that 
stores the number of observations of each value. Another way to think 
about this would be like table(fam) but with the results of table(fam) 
linked to each record. 

I tried: 

for (i in unique(fam)) { 
num <- sum(fam == i) 
} 

but it doesn't work, I think because of the i being the value itself rather than a handle? Idk. How would I do this? 

Thank you :)



More information about the R-help mailing list