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:
repis the function for the job. But try this instead:The way you’re using
applyhere,repis being called on each of the columns individually. It would be like callingrep(1:4), thenrep(c(3,5,3,7)), and combining the results into amatrix.applyis a great function to be familiar with, but it isn’t the tool for this job. In fact, a solution to this usingapplywould be pretty ugly:@MatthewLundberg demonstrates the appropriate way to do this with
applyin the comments.