[R] counting entries in vector

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Feb 4 17:08:21 CET 2009


try this:

k <- c("bb", "bb", "bb", "aa", "cc", "cc")

f <- factor(k, levels = unique(k))
as.vector(table(f))

you can put it in one line but it's less readable. I hope it helps.

Best,
Dimitris


axionator wrote:
> Hi all,
> I've a vector with entries, which are all of the same type, e.g. string:
> k <- c("bb", "bb", "bb", "aa", "cc", "cc")
> and want to create a second vector containing the number of each entry
> in k in the same order as in k, i.e.
> c(3, 1, 2)
> 
> or:
> k <- c(5,5,5,5,2,2,4)
> => c(4,2,1)
> 
> thanks
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list