0

I have a list that contains several lists. In each of these lists there is named numeric vector. For some lists, I want to change the names of this vector with a function. This function should allow me to specify the high-level list, and the group of nested lists I want to change.

Here's a toy example:

# construct a toy list

mylist <- list()

mylist[["type_1"]]$namednum <- c(runif(4))
names(mylist[["type_1"]]$namednum) <- c("A", "B", "C", "D")
mylist[["type_1"]]$somethingelse <- "something"

mylist[["type_2"]]$namednum <- c(runif(4))
names(mylist[["type_2"]]$namednum) <- c("A", "B", "C", "D")
mylist[["type_2"]]$somethingelse <- "something"

mylist[["type_3"]]$namednum <- c(runif(4))
names(mylist[["type_3"]]$namednum) <- c("A", "B", "C", "D")
mylist[["type_3"]]$somethingelse <- "something"

# function to change vector names within nested lists

renamefct <- function(element_names, element) {
  for(i in element_names) {
    names(element[[i]]$namednum) <- c("Var1", "Var2", "Var3", "Var4")
    print(names(element[[i]]$namednum))
  }
}

# vector specifying which nested lists to change

element_names1 <- c("type_1", "type_3")

When I now run the function like this:

renamefct(element_names1, mylist)

names(mylist[["type_1"]]$namednum) # see whether change has happened

I see that the function does its job, but not for the object in the global environment. From posts like this I understand that it has to do with the fact that the function modifies a copy of the object in the local namespace, and the need to write replacement functions. However, definining my function as suggested in the linked post:

`renamefct<-` <- function(element_names, element) {
  for(i in element_names) {
    names(element[[i]]$namednum) <- c("Var1", "Var2", "Var3", "Var4")
    print(names(element[[i]]$namednum))
  }
}

throws me an error:

Error in renamefct(element_names1, mylist) : could not find function "renamefct"

Note: I am aware that there probably better ways than the loop, but taking one step at a time.

broti
  • 1,338
  • 8
  • 29

1 Answers1

0

Modified function:

renamefct <- function(element_names, element) {
  for(i in element_names) {
    names(element[[i]]$namednum) <- c("Var1", "Var2", "Var3", "Var4")
  }
  return(element)
}

This works:

mylist <- renamefct(element_names1, mylist)

names(mylist[["type_1"]]$namednum) 
[1] "Var1" "Var2" "Var3" "Var4"
broti
  • 1,338
  • 8
  • 29