0
y <- list(a = 1, b = 2)
y["b"] <- list(NULL)

works well.

Then I tried below scripts but failed:

> list(a = 1, b = 2)['b']<-list(NULL)
Error in list(a = 1, b = 2)["b"] <- list(NULL) : 
  target of assignment expands to non-language object

I checked previous post,then tried assign:

> assign(list(a = 1, b = 2)['b'],list(NULL))
Error in assign(list(a = 1, b = 2)["b"], list(NULL)) : 
  invalid first argument

I think list(a = 1, b = 2)['b'] equal to y["b"],what's wrong with list(a = 1, b = 2)['b']<-list(NULL)?

kittygirl
  • 2,255
  • 5
  • 24
  • 52
  • It is the difference between `x <- 1` followed by `x <- 2` versus `1 <- 2`. What is the latter even supposed to mean? – John Coleman May 24 '20 at 15:40
  • @JohnColeman,then I will create a Intermediate variable just for assign value? – kittygirl May 24 '20 at 15:42
  • If it is going to be by assignment, you need a valid target. Perhaps there is some other way to mutate a list other than by assigning to a component. – John Coleman May 24 '20 at 15:47
  • 1
    What is the use-case of creating a list only to modify it even before you assign it to a variable? Why not just directly create the list that you want? This seems like a possible XY problem. – John Coleman May 24 '20 at 15:57
  • I just use this example for technical discussion.I think there's method to assign value directly without intermediate variable. – kittygirl May 24 '20 at 15:59

1 Answers1

1

You could write your own function:

change <- function(my_list,name,value){
    my_list[name] <- value
    my_list
}

Then change(list(a = 1, b = 2),'b',list(NULL)) works as (possibly) expected, although the semantics is that it creates a new list rather than modifies the old one. If you really wanted to modify an anonymous list in place, perhaps Rcpp could be used to do so with pointers.

John Coleman
  • 51,337
  • 7
  • 54
  • 119