0

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

renamne Thank you very much!

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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) 

4 Comments

First of all, thank you very much for your quick answer, but in fact I didn't seem to state my question clearly. 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.
@Alen Have you checked the solution at the end with match.fun
@Alen Do you want to create object names SCE1, SCE2 etc with the input 1, 2, ..
If you use for examplelapply, you can loop over a block of code that returns the last statement to you in a list when done. Could you work with that? Creating dynamic variable names is seldom the right answer and a good indication that something can be done better in another way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.