append a globally defined list from inside of a function in R

136 Views Asked by At

I am using the walk function to iterate over my list of lists and append a list element to every sub-list.

.insideFunction <- function(sublistName, arg2){

newListElement <- "Hello"
newListElement <- as.list(newListElement)
names(newListElement) <- "newListElement"

myList[[sublistName]] <- append(myList[[sublistName]], newListElement)

}


walk(names(myList), .insideFunction, someTable)

The problem is that the list myList, which is defined globally doesn't change. I am currently using the global assignment operator inside of the .insideFunction to force R to overwrite the sublist.

myList[[sublistName]] <<- append(myList[[sublistName]], newListElement)

How can I avoid using the global assignment operator, but still append the globally defined list from inside a function?

1

There are 1 best solutions below

6
On

Use map instead of walk to create a modified version of a list by applying a function to every element e.g. add 2 to each sub list:

library(purrr)

data <- list(
  list("foo", 1),
  list("bar", 1)
)
data
#> [[1]]
#> [[1]][[1]]
#> [1] "foo"
#> 
#> [[1]][[2]]
#> [1] 1
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [1] "bar"
#> 
#> [[2]][[2]]
#> [1] 1

newListElement <- "Hello"
newListElement <- as.list(newListElement)
names(newListElement) <- "newListElement"

data %>% map(~ .x %>% c(newListElement))
#> [[1]]
#> [[1]][[1]]
#> [1] "foo"
#> 
#> [[1]][[2]]
#> [1] 1
#> 
#> [[1]]$newListElement
#> [1] "Hello"
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [1] "bar"
#> 
#> [[2]][[2]]
#> [1] 1
#> 
#> [[2]]$newListElement
#> [1] "Hello"

Created on 2022-04-22 by the reprex package (v2.0.0)