I am trying to build a single vector that holds elements of several vectors with different lengths. As an example, let’s consider three vectors:
x <- rnorm(5,0,1)
y <- rnorm(2,0,1)
z <- rnorm(3,0,1)
To get this done in a handy, I used the sapply function as follows
set.seed(123)
vec <- sapply(c(5,2,3), function(n) rnorm(n,0,1))
but this lists them as separate vectors
[[1]]
[1] -0.5605 -0.2302 1.5587 0.0705 0.1293
[[2]]
[1] 1.715 0.461
[[3]]
[1] -1.265 -0.687 -0.446
Is there away of improving this code or applying some other functions to have the three vectors as a single vector so that it appears as
[1] -0.5605 -0.2302 1.5587 0.0705 0.1293 1.715 0.461 -1.265 -0.687 -0.446
Any help is well appreciated.
>Solution :
We can use unlist
to convert a list into a vector.
unlist(sapply(c(5,2,3), function(n) rnorm(n,0,1)))
[1] 0.2185724 -1.4715697 -1.5881170 -0.5791368 -1.1028307
[6] -0.5208913 -0.7065582 0.1414712 0.6883996 0.3030542