Home > Mobile >  From list of lists to a data frame keeping the number of the list
From list of lists to a data frame keeping the number of the list

Time:11-17

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

Any clue?

CodePudding user response:

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