I am trying to change a list into a dataframe. Each element of the list may have an unequal length of values. An example list is given here:
a = c(1:9)
b = c(10:14)
test_list = list(a, b)
print(test_list)
#> [[1]]
#> [1] 1 2 3 4 5 6 7 8 9
#>
#> [[2]]
#> [1] 10 11 12 13 14
And the desired result is given here:
desired_result = data.frame(var1 = c(rep(1,9), rep(2,5)),
var2 = c(1:14))
print(desired_result)
#> var1 var2
#> 1 1 1
#> 2 1 2
#> 3 1 3
#> 4 1 4
#> 5 1 5
#> 6 1 6
#> 7 1 7
#> 8 1 8
#> 9 1 9
#> 10 2 10
#> 11 2 11
#> 12 2 12
#> 13 2 13
#> 14 2 14
Created on 2023-07-24 with reprex v2.0.2
>Solution :
Give names to the list and then stack():
stack(setNames(test_list, seq_along(test_list)))[2:1]
# ind values
# 1 1 1
# 2 1 2
# 3 1 3
# 4 1 4
# 5 1 5
# 6 1 6
# 7 1 7
# 8 1 8
# 9 1 9
# 10 2 10
# 11 2 11
# 12 2 12
# 13 2 13
# 14 2 14