In my R function, I am dealing with a character string containing the name of an object that is sitting somewhere in the workspace. I would like to overwrite the object (e.g., convert the object to a matrix).
However, I only know the name of the object as a character string, and I don't have the object reference. I know I can convert the character string to an object reference either by using the get(x)
function (where x
is the string referring to the object), or by something like eval(as.name(x))
. However, this works only for accessing the object, not for overwriting the object.
How can I achieve this? Here is some code:
myvector <- 1:5 # my object
x <- "myvector" # text representation of the object
get(x) <- as.matrix(get(x)) # my first attempt
eval(as.name(x)) <- as.matrix(eval(as.name(x))) # second attempt
Note that the first line is not part of the function from which I want to overwrite this object in the workspace, so I cannot just write myvector <- as.matrix(myvector)
.