Cenoc
Cenoc

Reputation: 11670

Combine output of apply into an array in R

Suppose I have the following,

    ID   Times
    555   1
    444   4
    777   5  

I would like to get the output of [555,444,444,444,444,777,777,777,777,777] (it get an array with the number of times in column Times of ID). I tried the following:

apply(dat, 1, function(d) rep(d['ID'], times = d['Times']))

But this comes out as a list and I can't find a way of merging that into an array. Any help would be very much appreciated.

Upvotes: 3

Views: 64

Answers (2)

Chris Watson
Chris Watson

Reputation: 1367

This should work:

> unlist(mapply(rep, dat$ID, dat$Times))
[1] 555 444 444 444 444 777 777 777 777 777

Upvotes: 1

agstudy
agstudy

Reputation: 121588

Simply using rep:

with(dx,rep(ID,Times))
## 555 444 444 444 444 777 777 777 777 777

Upvotes: 6

Related Questions