I have two vectors
x <- c(2, 3, 4) y <- rep(0, 5)
I want to get the following output:
> z 2, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0
How to create z ? I tried using paste and c , but nothing works. The only thing I can think of is to use for() , and it is terribly slow. I have googled this, and I'm sure the solution is there, and I just don't click on the right keywords.
UPDATE: For benchmarking purposes:
Using Nicola's solution:
> system.time( + precipitation <- `[<-`(numeric(length(x)*(length(y)+1)),seq(1,by=length(y)+1,length.out=length(x)),x) + ) user system elapsed 0.419 0.407 0.827
This is ridiculously fast! I have to say! Can someone please explain this to me? My for() , which I know, is always erroneous in R , would take at least one day if it even finished.
Other offers:
> length(prate) [1] 4914594 > length(empty) [1] 207 > system.time( + precipitation <- unlist(sapply(prate, FUN = function(prate) c(prate,empty), simplify=FALSE)) + ) user system elapsed 16.470 3.859 28.904
I had to kill
len <- length(prate) precip2 <- c(rbind(prate, matrix(rep(empty, len), ncol = len)))
In 15 minutes.