Hi, I have a list of dataframes and am attempting to add a new "group_id" column to each dataframe that is equal to its index number to help keep track of which list each dataframe came from after combining them . I thought names()
might do it but it takes the name of the column rather than from the list. The example below shows this, but my goal is to have group_id equal to "1" for the rows that came from list index 1, and equal to "2" for the rows that came from index 2, and so on.
library(tidyverse)
list_df <- list(data.frame(v = runif(5)),
data.frame(v = runif(5)),
data.frame(v = runif(5)))
list_df %>%
map_df(~mutate(., group_id = names(.)))
#> v group_id
#> 1 0.496321408 v
#> 2 0.818124269 v
#> 3 0.121642510 v
#> 4 0.214708877 v
#> 5 0.096863223 v
#> 6 0.006266511 v
#> 7 0.080018796 v
#> 8 0.932205413 v
#> 9 0.959364793 v
#> 10 0.973954420 v
#> 11 0.100228835 v
#> 12 0.240053172 v
#> 13 0.062018736 v
#> 14 0.089113555 v
#> 15 0.513639775 v
Created on 2022-11-03 by the reprex package (v2.0.1)