Reputation: 33
In R , how to use the value of a variable as the name of another variable
for example:
SCE<-function(i){
#x<-paste0("SCE",i)
x<-c(i,i+1)
return (x)
}
x<-paste0("SCE",1)
y<-SCE(1)
paste0("SCE",1)=SCE(1)
cat("SCE",1)=SCE(1)
How can I make the value of variable x (string) as the name of another variable y (unknown data type)? Here, the final result I want to get is a variable named SCE1, its type is numeric, and its value is 1 2
The problem I actually encountered is: I have a repetitive code that I want to use a for loop to complete, but every time I complete it, I want to save the result as a variable so that I can use it later.
SCE<-function(i){
#x<-paste0("SCE",i)
x<-c(i,i+1)
return (x)
}
for (i in 2:9) {
x<-paste0("SCE",i)
y<-SCE(i)
}
Every time the for loop is completed, I hope to get a variable of SCE+number, whose value is the result of the corresponding SCE function
Upvotes: 0
Views: 93
Reputation: 887851
The value of
paste0("SCE", 1)
#[1] "SCE1"
We may need the brackets as well
x <-paste0("SCE(", 1, ")")
and then do an eval(parse
eval(parse(text = x))
#[1] 1 2
which is same as executing the function
y <- SCE(1)
y
#[1] 1 2
If the OP wanted to get the values from "SCE1", then extract the function part and the input argument separately
match.fun(sub("\\d+", "", x))(as.numeric(sub("\\D+", "", x)))
#[1] 1 2
If we want to create objects in the global environment (not recommended), an option is list2env
, though it is better to store it in a named list
lst1 <- setNames(lapply(1:5, SCE), paste0("SCE", 1:5))
list2env(lst1, .GlobalEnv)
Upvotes: 1
Reputation: 41260
if I understand your question correctly, assign
could be an option :
SCE<-function(i){
assign(x = paste0("SCE",i), value = c(i,i+1), envir = parent.frame())
}
SCE(1)
SCE1
#> [1] 1 2
Upvotes: 1