How can I use replication function in the following situation:
mydata <- data.frame (var1 = 1:4, replication = c(3, 5, 3, 7))
mydata
var1 replication
1 1 3
2 2 5
3 3 3
4 4 7
I want a result like this:
1,1,1, 2,2,2,2,2, 3,3,3, 4,4,4,4,4,4,4
1 is repeated 3 times, 2 for 5 times and so on
I tried apply function, do not do any thing good.
apply (mydata,2,rep )
You were on the right track: rep
is the function for the job. But try this instead:
with(mydata, rep(var1, replication))
The way you're using apply
here, rep
is being called on each of the columns individually. It would be like calling rep(1:4)
, then rep(c(3,5,3,7))
, and combining the results into a matrix
.
apply
is a great function to be familiar with, but it isn't the tool for this job. In fact, a solution to this using apply
would be pretty ugly:
unlist(apply(mydata, 1, function(var1.rep) do.call(rep, unname(as.list(var1.rep)))))
@MatthewLundberg demonstrates the appropriate way to do this with apply
in the comments.