I'd use sapply
and unlist
:
dat = unlist(sapply(3:1, function(x) rep(myd, each = x)))
all.equal(dat, myh)
[1] TRUE
Question
I wanted to repeat a vector which contain 11 elements 3, 2 and 1 time and tried the following awkward code which gave me what I wanted (a vector of 66. How could I do that in a better way?
myd<-paste(letters[1:11])
mye<-rep(myd,each =3)
myf<-rep(myd,each =2)
myg<-rep(myd,each =1)
myh<-c(mye,myf,myg)
length(myh)
[1] 66
Solution
I'd use sapply
and unlist
:
dat = unlist(sapply(3:1, function(x) rep(myd, each = x)))
all.equal(dat, myh)
[1] TRUE
OTHER TIPS
Use sapply
:
unlist(sapply(3:1,function(x)rep(myd,each=x)))
This isn't really a serious entrant. Just wanted to show that the paste()
operation to myd
was entirely superfluous, and that you can get patterned selection from sequences:
mye <-rep( letters[1:11], each =3)
myh <-c(mye, mye[c(TRUE,TRUE, FALSE)] , mye[c(TRUE,FALSE, FALSE)] )
The c(TRUE,TRUE, FALSE) and c(TRUE,FALSE, FALSE) will get recycled by "["
so that every third item is omitted in the first case and every third item is selected en the second case.