Reputation: 117
I am quite new in R programming and facing a simple problem but can't find any solution.
In other programming languages, it is possible to generate incrementally named variables into a loop. Is this possible in R? How?
For example, I would like to save the output of an operation into a new variable each time a loop is done:
for(i in 1:5) {
var_[i] <- i + pi
}
In this way, I would end up with var_1
, var_2
,..., var_5
.
Thank you in advance for any help.
Upvotes: 0
Views: 462
Reputation: 206486
While this is possible in R, it is highly discouraged. It is better to work with named lists or vector or accumulate results. For example here you can store them as a vector.
myvar<-1:5+pi
# myvar[1] == 4.141593
# myvar[5] == 8.141593
or if you wanted to create a list you could use
myvar <- lapply(1:5, function(x) {x+pi})
names(myvar)<-paste("var", 1:5, sep="_")
# myvar[["var_1"]] == myvar[[1]] == 4.141593
But if you really need to create a bunch of variables (and you don't) you can use the assign()
function
Upvotes: 2
Reputation: 173677
The literal version of what you're attempting is generally considered bad practice in R.
We generally avoid creating large collections of isolated data structures. It is much cleaner to put them all in a list and then set their names attribute:
x <- vector("list",5)
for (i in seq_len(5)){
x[[i]] <- i + pi
}
names(x) <- paste0("var_",1:5)
And then you'd refer to them via things like:
x[["var_1"]]
Upvotes: 5