[R] avoiding a loop?

Tom Sgouros tomfool at as220.org
Mon Oct 15 20:21:29 CEST 2007

Hi All:

I feel like there must be a slick R-native no-loop way to get the counts
for the entries in a factor, but I'm unable to see how.  Right now I'm
doing this:

hn.ent<-data.frame(rep(0,length(levels(hnf))), row.names=levels(hnf))
for (lev in levels(hnf)) {
  hn.ent[lev,"count"] <- sum(lev == hnf)

I'm sure there's a better way, but I don't know it.  Can anyone help?

Also, why does hn.ent[lev,"count"] work and hn.ent$count[lev] does not?

In a related problem, I have a vector of strings, and want a vector of
the strings combined.  That is, I have c("a", "b", "c", "d") and I want
c("ab", "bc", "cd").  I see this is easy with numbers, but paste() is
the only way I see to stick strings together, and I don't get how I'd
use them without a loop.

Many thanks,


 tomfool at as220 dot org

More information about the R-help mailing list