Why doesn't assign() values to a list element work in R?

好久不见. 提交于 2020-01-01 04:23:09

问题


I'm trying to use assign values in an object in a list. What I want to do is change some elements. For example:

x <- list()
x$test <- 1
assign("x$test", 2)
x$test == 1
     [1] TRUE

Any thoughts? I need to use assign because I am building a function which will take the names of the objects within the list (x) as inputs.


回答1:


Looks like you're out of luck. From the help file:

‘assign’ does not dispatch assignment methods, so it cannot be used to set elements of vectors, names, attributes, etc.

Note that assignment to an attached list or data frame changes the attached copy and not the original object: see ‘attach’ and ‘with’.

If you're passing names(x) as input, couldn't you use:

nms <- names(x)
for ( n in nms )
    x[[n]] <- 'new_value'

Also, are you intending for your function to modify some global variable? e.g.:

x <- list(test=1)

f <- function(...)
   x$test <- 2

f() # want x$test = 2 ??

Because this won't work (scope problems). You can make it work with a bit of footwork (<<-), but this is generally considered bad practice as it's easy to intrtoduce unintentional bugs into your code.

If you could give an example of why you want this function/what purpose it will serve, we could help you find an alternative solution.




回答2:


See what happens when you assign to "x$test":

x <- list()
x$test <- 1
assign("x$test", 2)
ls()
[1] "x"      "x$test"

The element "test" in "x" is still 1, and you extract it with x$test but get("x$test") will be the value 2 from that name.

Why not just use the names directly? I.e.

this.name <- "test"
x[[this.name]] <- 2



回答3:


Another solution is:

x <- list()
x$test <- 1
assign("x$test", 2)
x$test == 1
TRUE
eval(parse(text="x$test<-2"))
x$test == 1
FALSE

The eval(parse(text="")) command can be very useful in this context.

Sincerely




回答4:


Have you tried <<- ? I used this to assign names and values to a list from within a function in a post yesterday (see "Combine a series of data frames and create new columns for data in each").



来源:https://stackoverflow.com/questions/9561053/why-doesnt-assign-values-to-a-list-element-work-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!