DerDressing
DerDressing

Reputation: 315

Unlist nested list by name

I import a nested list of unknown length (here 2) and unknown names (here iter1 and iter2) and get the names of the list:

iter1 <- list(1, 2, 3, 4)
iter2 <- list(1, 2, 3, 4)

nested_list <- list(iter1 = iter1, iter2 = iter2)

names <- names(nested_list)

The next thing I want to do is actually this:

unlist <- data.frame(x=unlist(nested_list$iter1))

But due to the fact I don't know the names beforehand I want to do something like this:

unlist <- data.frame(x=unlist(nested_list$names[1]))

Which is certainly not working. There is no error, but the created list is empty.

In the end I want to do something like this:

for(i in 1:length(nested_list)) {
   unlist <- data.frame(x=unlist(nested_list$names[i]))
   print(unlist)
}

Upvotes: 1

Views: 164

Answers (3)

jay.sf
jay.sf

Reputation: 72828

Using Map, avoiding the names vector.

data.frame(Map(unlist, nested_list)[1])
#   iter1
# 1     1
# 2     2
# 3     3
# 4     4

Or, in order to give column names with mapply:

data.frame(x=mapply(unlist, nested_list)[,1])
#   x
# 1 1
# 2 2
# 3 3
# 4 4

The 1 in brackets indicates first list name, use 2 for the second name accordingly.


Data

nested_list <- list(iter1 = list(1, 2, 3, 4), iter2 = list(1, 2, 3, 4))

Upvotes: 1

cbo
cbo

Reputation: 1763

I am not sure I get what you intended as result, could you precise it if needed ?

iter1 <- list(1, 2, 3, 4)
iter2 <- list(1, 2, 3, 4)

nested_list <- list(iter1 = iter1, iter2 = iter2)
names <- names(nested_list)

cbind.data.frame(lapply(nested_list, unlist))
#>   iter1 iter2
#> 1     1     1
#> 2     2     2
#> 3     3     3
#> 4     4     4

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101373

Maybe you can try the code below

unlist <- data.frame(x=unlist(nested_list[names[1]]))

such that

       x
iter11 1
iter12 2
iter13 3
iter14 4

Upvotes: 1

Related Questions