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

From list of lists to a data frame keeping the number of the list

I have a list of lists similar to df.

x <- list("a" = 3:5, "b" = 2:4,"c" = 1:3)
y <- list("a" = 1:3, "b" = 2:4,"c" = 3:5)
df <- list(x, y)

I convert the list of lists (df) into a data frame (data) following the next command:

data <- do.call(rbind.data.frame, df)

However, in data I want to keep the number of the list as a new variable (in this case, value 1 for the first 3 lines of data and 2 for the last 3 lines of data???

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

Any clue?

>Solution :

use bind_rows with .id – by default if the list is unnamed, the column created (‘grp’) will return will the sequence of the list

library(dplyr)
bind_rows(df, .id = 'grp')

-output

# A tibble: 6 × 4
  grp       a     b     c
  <chr> <int> <int> <int>
1 1         3     2     1
2 1         4     3     2
3 1         5     4     3
4 2         1     2     3
5 2         2     3     4
6 2         3     4     5
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