Home > Software design >  Update lists elements programmatically looping through the lists names
Update lists elements programmatically looping through the lists names

Time:11-04

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
}

CodePudding user response:

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
  • Related