I have a for loop:
for (i in 1:10){ Ai=d+rnorm(3)}
What I would like to do is have A1, A2,A3...A10
and I have the variable i
in the variable name.
It doesn't work this way, but I'm probably missing some small thing. How can I use the i
in the for loop to assign different variable names?
This question is related to
r
You could use assign
, but using assign
(or get
) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.
with a list:
A <- lapply (1 : 10, function (x) d + rnorm (3))
with a matrix:
A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
Another option is using eval and parse, as in
d = 5
for (i in 1:10){
eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}
Source: Stackoverflow.com