assign is good, but I did not find a function to go back to the variable that you created in the automatic script. ( as.name seems to work the other way around). More experienced coders will undoubtedly have a better solution, but this solution works and seems to be a bit humorous as it allows R to write code for itself.
Let's say I just assigned the value 5 to x ( var.name <- "x"; assign(var.name, 5) ), and I want to change the value to 6. If I write a script and donβt know in advance what variable name ( var.name ) will be (which seems to be the point of the assign function), I can't just put x <- 6 , because var.name could be "y" . Therefore I:
var.name <- "x" #some other code... assign(var.name, 5) #some more code... #write a script file (1 line in this case) that works with whatever variable name write(paste0(var.name, " <- 6"), "tmp.R") #source that script file source("tmp.R") #remove the script file for tidiness file.remove("tmp.R")
x will be changed to 6, and if the variable name was something other than "x" , this variable will be similarly changed to 6.
CJB Jul 14 '15 at 15:54 2015-07-14 15:54
source share