I'll just say it once more: if you need to rename variables in R, just use the rename() function.
Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.)
d <- 5
for(i in 1:10) {
nam <- paste("A", i, sep = "")
assign(nam, rnorm(3)+d)
}
More info here or even here!
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]))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With