[R] [solved] How to count numbers of a vector and use them as index values?

Paul Menzel paulepanter at users.sourceforge.net
Mon Aug 1 00:37:34 CEST 2011


Am Sonntag, den 31.07.2011, 15:19 -0700 schrieb Jeffrey Dick:
> Here's an attempt using sapply:
> 
> > x <- c(2, 2, 3, 3, 4, 6)
> > ys <- 1:8
> > sapply(ys, function(y) { length(which(x==y)) } )
> [1] 0 2 2 1 0 1 0 0

The last piece for my trials missing was `sapply()` which I overlooked
reading `?lapply()` inspired by [1].

So an alternative is

> x <- c(2, 2, 3, 3, 4, 6)
> ys <- 1:8
> sapply(ys, function(y) { sum(x==y) } )
[1] 0 2 2 1 0 1 0 0

which is of course overkill reading Dénes’ response.

> tabulate(x, 8)
[1] 0 2 2 1 0 1 0 0


Thank you all,

Paul


[1] http://www.r-bloggers.com/thinking-in-r-vectors/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20110801/d7a321c9/attachment.bin>


More information about the R-help mailing list