1

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?

Nneka
  • 1,764
  • 2
  • 15
  • 39

1 Answers1

0

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)

danlooo
  • 10,067
  • 2
  • 8
  • 22
  • is there maybe a problem with the append function? I change it to map and still nothing happens – Nneka Apr 22 '22 at 12:30
  • `.insideFunction` must be defined before `map` and not inside. See my revised answer. – danlooo Apr 22 '22 at 12:34
  • yes, sorry my bad. I edited the question as well. So I firstly defined the .insideFunction, which I then use in the map. The function does more than just appending. The append is the last step in the function. But still no change in the global object myList – Nneka Apr 22 '22 at 12:39
  • it seems that you are not using any inside function in your map? – Nneka Apr 22 '22 at 12:41
  • The formula `~ .x %>% c(newListElement)` is to define the function I want to apply to each element. It will be converted internally e.g. to `data %>% map(function(x) {c(x, newListElement)})`. This function is anonymous without any explicit name e.g. `.insideFunction`. You do not need names if the function is not being called elsewhere. – danlooo Apr 22 '22 at 12:45
  • The first argument of map is the list and not the names. The second is the function or formula: `map(seq(5), function(x){ x + 1 })` – danlooo Apr 22 '22 at 12:50