R Unlist list and assign element position

3954 views r
2

I've got a List of which I show element 999.

enter image description here

I need to convert it into a data.table in which the element number is assigned as follows:

enter image description here

Tried different possible solutions but nothing seems to be working properly.

answered question

Tried what "different possible solutions"?

for example as.data.table(t(x)) where x is my list

1 Answer

9

You can use do.call('rbind', ...) to get a dataframe from your list, and rep() on the list's indices with the times argument set to sapply(l, nrow) (where l is the name of your list) to get the desired element numbers:

# Make an example list
l <- list(data.frame(a = 1:3, b = 4:6), data.frame(a = 7:8, b = 8:9))
l
#> [[1]]
#>   a b
#> 1 1 4
#> 2 2 5
#> 3 3 6
#> 
#> [[2]]
#>   a b
#> 1 7 8
#> 2 8 9
# Get a dataframe from it
df <- do.call('rbind', l)
# Add the element numbers by repeating the indices of the list,
# each as many times as the number of rows in that element's dataframe
df$element_number <- rep(seq_along(l), times = sapply(l, nrow))
df
#>   a b element_number
#> 1 1 4              1
#> 2 2 5              1
#> 3 3 6              1
#> 4 7 8              2
#> 5 8 9              2

Created on 2018-11-04 by the reprex package (v0.2.1)

posted this

Have an answer?

JD

Please login first before posting an answer.