Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Name second level of nested list in R

I have a nested list similar to the following dummy:

list1 <- list(1:3, 4:7, 8:10)
list2 <- list(2:5, 4:9, 19:23, 15:18)
list3 <- list(1:5)

nested_list <- list(list1, list2, list3)
names(nested_list) <- c("first", "second", "third")

The first level is named, while the second level is not. I would like to assign names to the second level of the list based on the first level names and pos indices, so the structure of this list would look like this:

List of 3
 $ first :List of 3
  ..$ first_1: int [1:3] 1 2 3
  ..$ first_2: int [1:4] 4 5 6 7
  ..$ first_3: int [1:3] 8 9 10
 $ second:List of 4
  ..$ second_1: int [1:4] 2 3 4 5
  ..$ second_2: int [1:6] 4 5 6 7 8 9
  ..$ second_3: int [1:5] 19 20 21 22 23
  ..$ second_4: int [1:4] 15 16 17 18
 $ third :List of 1
  ..$ third_1: int [1:5] 1 2 3 4 5

Does anyone know how to solve this? I would be grateful for help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How about a for loop?

for (i in seq_along(nested_list)) {
   names(nested_list[[i]]) <- paste(names(nested_list)[i], 
                                    seq_along(nested_list[[i]]), 
                                    sep = "_")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading