How can I overwrite an object in R if I only know the name of the object as a character string?

StackOverflow https://stackoverflow.com/questions/17522948

Вопрос

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).

Это было полезно?

Решение

You try to assign by name a global variable within a function. Why? Should avoid to manipulate global variable and as said in the comment should exist better manner to deal with your problem and avoid global variable side effect.
You should use assign to change value by name. By default, it changes value in the current environment(local), So you should also set in which environment your variable is defined. Something like this :

 assign( x , as.matrix(get(x)),envir=.GlobalEnv)

Or , tell assign to search until it encounters the variable :

 assign( x , as.matrix(get(x)),inherits=TRUE)

EDIT better solution

  1. Return the new value and assign it later in the global environment

    assign( x , function(x){....})
    
  2. If the variable is kind of global setting you can define an environment where your define myvector.

    myoptions <- new.env()
    myoptions$myvalue <- 1:5
    function(x){ assign(x,newvalue,myoptions )}
    
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top