[R] how to create data.frames from vectors with duplicates

Marc Schwartz marc_schwartz at me.com
Wed Aug 31 18:58:36 CEST 2011


On Aug 31, 2011, at 11:45 AM, zhenjiang xu wrote:

> Hi R users,
> 
> suppose I have two vectors,
>> x=c(1,2,3,4,5)
>> y=c('a','b','c','a','c')
> How can I get a data.frame like this?
>> xy
>      count
> a     5
> b     2
> c     8
> 
> I know a few ways to fulfill the task. However, I have a huge number
> of this kind calculations, so I'd like an efficient solution. Thanks


See ?rep and ?as.data.frame.table

Try this:

> data.frame(table(rep(y, x)))
  Var1 Freq
1    a    5
2    b    2
3    c    8

HTH,

Marc Schwartz



More information about the R-help mailing list