add a new column to list of dataframes equal to the list index number

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)

1 Like

Would using the bind_rows function work for you?

If you name the items in your list, like so:

library(tidyverse)

list_df <- list("first" = data.frame(v = runif(5)),
                "second" = data.frame(v = runif(5)),
                "third" = data.frame(v = runif(5)))

You can use bind_rows, and its .id argument for exactly this purpose.

bind_rows(list_df, .id = "group_id")
#>    group_id          v
#> 1     first 0.63793932
#> 2     first 0.07537758
#> 3     first 0.30601957
#> 4     first 0.25694269
#> 5     first 0.93665605
#> 6    second 0.44209007
#> 7    second 0.17167989
#> 8    second 0.55728364
#> 9    second 0.46265454
#> 10   second 0.24441218
#> 11    third 0.58652945
#> 12    third 0.85716510
#> 13    third 0.67078222
#> 14    third 0.27022973
#> 15    third 0.22795737

Created on 2022-11-03 with reprex v2.0.2

Yes, thank you thank you. This works, even without naming each element of the list.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.