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

How to expand a list in R

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

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 :

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
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