Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

r

assign

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.

like image 491
mike Avatar asked Mar 05 '12 02:03

mike


People also ask

What does assign () do in R?

In R programming, assign() method is used to assign the value to a variable in an environment.

How do you assign a value to an object in R?

Objects are assigned values using <- , an arrow formed out of . (An equal sign, = , can also be used.) For example, the following command assigns the value 5 to the object x . After this assignment, the object x 'contains' the value 5.

How do I assign a name to a list in R?

The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.


2 Answers

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.

like image 186
mathematical.coffee Avatar answered Oct 13 '22 01:10

mathematical.coffee


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

like image 20
Marc Girondot Avatar answered Oct 12 '22 23:10

Marc Girondot