Reputation: 41
I want to create a new variable when i´m running a loop. For example, in a for loop from 1 to 10, create the variable t1, t2, t3 and so on.
for i in 1:10{
Ti=i
}
How can i do this?
Thanks a lot.
Upvotes: 0
Views: 620
Reputation: 433
I wonder why you would do this, but there is a way too do this. There's a function in R called assign
. You can write
for (i in 1:10) {
assign(paste0("T", i), i, envir = .GlobalEnv)
}
# Check that we have those variables
ls()
#> [1] "i" "T1" "T10" "T2" "T3" "T4" "T5" "T6" "T7" "T8" "T9"
The first argument to assign
is the name of the variable. The second is the value to be assigned to the variable. The third is the environment in which the variable shall live. Here I put the variable into the global environment.
That said, a better way to approach this kind of problem is to use the apply
family of functions, which generates a vector that stores the output of each iteration of the loop, or to first start a vector, and then fill in the vector; this way the values you are generating in the for loop are kept in the same place and are easier to organize and compute with. R is very vectorized.
Edit: Another piece of advise: global assignment is often considered bad, because it may add cryptic dependencies, making code hard to debug when something goes wrong.
Upvotes: 2