2

I have a few datasets that I'm merging together with bind_rows. My code looks like this

df1 <- data.frame(v1 = 1:10, v2 = 11:20)
df2 <- data.frame(v1 = 11:20, v2 = 1:10)

list(df1, df2) %>%
  bind_rows(.id = "name")

I want the name column to read "df1" for df1 and "df2" for df2. I know I can use set_names() to do this manually...

list(df1, df2) %>%
  set_names(c("df1", "df2")) %>%
  bind_rows(.id = "name")

...but I want a way to do this programatically that works no matter what the dataset names are. How can I do this?

ila
  • 709
  • 4
  • 15

1 Answers1

6

We can use dplyr::lst or purrr::lst which would automatically return a named list with the arguments

library(dplyr)
dplyr::lst(df1, df2) %>%
  bind_rows(.id = "name")
#   name v1 v2
#1   df1  1 11
#2   df1  2 12
#3   df1  3 13
#4   df1  4 14
#5   df1  5 15
#6   df1  6 16
#7   df1  7 17
#8   df1  8 18
#9   df1  9 19
#10  df1 10 20
#11  df2 11  1
#12  df2 12  2
#13  df2 13  3
#14  df2 14  4
#15  df2 15  5
#16  df2 16  6
#17  df2 17  7
#18  df2 18  8
#19  df2 19  9
#20  df2 20 10
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Wow, and it's super fast to boot! I'm going to wait a bit to pick this answer because I seem to remember another way to do it and I want to see if someone else chimes in, but this is good. – ila Sep 16 '20 at 23:59