How can I extract many sublists at once in R?

65 Views Asked by At

I am new to R and dealing with this large list called "times.list" (see image) List. Here, to extract my vectors from 1 to 4 (marked in red) I just "unlist" each one of them, and create new objects like so:

data1 <- unlist(times.list [[1]] [1])
data2 <- unlist(times.list [[1]] [2])
data3 <- unlist(times.list [[1]] [3])
data4 <- unlist(times.list [[1]] [4])

Instead of doing this over and over x the number of vectors I have (my list is [1x113] in this case), is there a way to extract these data at once, and assign a name to all of them? Ideally I would like to extract only a subset (in this example data2, data4) based on a vector:

dataIneed <- c(2, 4)

Thank you so much!

Based on my vector:

dataIneed
                                                                                                                                                                                                           
2   4   

I do:

data2 <- unlist(times.list [[1]] [2])
data4 <- unlist(times.list [[1]] [4])

It works perfectly but it's not practical at all, it takes forever because in reality I have >100 vectors to extract.

1

There are 1 best solutions below

0
Konrad Rudolph On

To extract multiple elements of a list, use indexing: mylist[index].

as.data.frame(mylist) is sufficient to convert your list to a data.frame. You do not ever need to put your columns into separate variables first, and doing so is convoluted and pollutes your global environment with unnecessary temporary variables. If you want to assign custom column names you can then use setNames().

If you want to extract sublists/unlist, lapply(mylist, unlist) is your friend.

Putting it all together:

extracted_data <- lapply(times.list[dataIneed], unlist)
result <- setNames(as.data.frame(extracted_data), paste0("data", dataIneed))