'Assign names to sublists in a list

I have a list that contains three sublists, each of those sublists containing two objects. Now I am looking for an efficent way to assign names to those objects in the sublists. In this case, the single objects of each sublist are supposed to have the same names (Matrix1 and Matrix2).

Here is a easy reproducible example:

# create random matrices
matrix1 <- matrix(rnorm(36),nrow=6)
matrix2 <- matrix(rnorm(36),nrow=6)

# combine the matrices to three lists
sublist1 <- list(matrix1, matrix2)
sublist2 <- list(matrix1, matrix2)
sublist3 <- list(matrix1, matrix2)

# combine the lists to one top list
Toplist <- list(sublist1, sublist2, sublist3)

I can do this by using a for loop:

# assign names via for loop
for (i in 1:length(Toplist)) {
  names(Toplist[[i]]) <- c("Matrix1", "Matrix2")
}

I am sure there must be a more elegant way using a nested lapply command. But I struggled to implement the names() command inside it.

Anybody with a hint?

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source