I want to generate multiple random vectors:
a <- rnorm(10)
b <- rnorm(10)
c <- rnorm(10)
Is there a way to do this more concisely? For example, doing the following assigns the same numbers to a, b, c
, which is something I don't want.
a <- b <- c <- rnorm(10)
Another way is to use a for loop, but is there a more concise way?
CodePudding user response:
We can use zeallot
multiple assignment operator (%<-%
for this
library(zeallot)
c(a, b, c) %<-% replicate(3, rnorm(10), simplify = FALSE)
-checking
> head(a)
[1] 0.3268303 -0.3641770 -0.5644841 -1.9312762 0.1363512 1.5742827
> head(b)
[1] -0.2849812 -1.5234004 0.4008743 -0.4625301 0.9541247 0.6801852
> head(c)
[1] -0.8387253 2.1883784 -0.1846793 -0.8896609 -0.3637861 -1.1172537
It may be better to create a list
and name it instead of creating multiple objects in the global environment i.e.
lst1 <- setNames(replicate(3, rnorm(10), simplify = FALSE), letters[1:3])