0

I need to update lists elements programmatically looping through the lists names in R.

Is there a way to do that using some sort of Non-Standard Evaluation or another method?

Pseudo-code of a minimum example:

  x = list(a=1)
  y = list(a=3)
  
  for(i in c("x", "y")){
    
    i[["a"]] <- 10
  }

Expected results:

  x[["a"]] == 10
  y[["a"]] == 10

Edit: I found this way to update the values directly without making a copy of the lists via get(i):

x = list(a=1)
y = list(a=3)

.env = pryr::where("x")

for(i in c("x", "y")){
    
  .env [[ i ]] [[ "a" ]] <- 10
}
GitHunter0
  • 424
  • 6
  • 10

1 Answers1

1

The "x", "y" are strings, we need to get the value as well as assign

for(i in c("x", "y")) {
    tmp <- get(i)
    tmp[["a"]] <- 10
    assign(i, tmp)
}

-checking

> x
$a
[1] 10

> y
$a
[1] 10
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you, I forgot to mention that I do not want to copy the list via `get(i)` since the list can have a very large size. I will edit my question to include a solution I come up that can update the lists elements directly. – GitHunter0 Nov 03 '22 at 19:31
  • 1
    @GitHunter0 you can also use base R i.e.`.GlobalEnv[[i]][["a"]] <- 10` – akrun Nov 04 '22 at 14:50
  • Yes, but since I'm using Shiny, I have to get the specific environment. – GitHunter0 Nov 04 '22 at 18:47
  • @GitHunter0 You could define the objects in `global.R` and then source it if it is in shiny. – akrun Nov 04 '22 at 18:57
  • 1
    @GitHunter0 if it is reactive objects, you can also check [here](https://github.com/rjake/shinyobjects) – akrun Nov 04 '22 at 19:00