1

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?

vog
  • 770
  • 5
  • 11

1 Answers1

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi @akrun , how would you use the proposed code in the following context ``` lapply(df, function(x) do.call(rbind, x))```? – vog Dec 03 '21 at 13:22
  • @vog If it is a list, you may use `purrr::map(lst1, ~ bind_rows(.x, .id = "grp"))` – akrun Dec 03 '21 at 16:34