0

I'm appending multiple data frames into a larger dataframe using rbind. I would like to add the name of the data frame as a new column, "name".

n = c(2, 3, 5) 
s = c("aa", "bb", "cc") 
d1 = data.frame(n, s)     

n = c(2, 3, 5) 
s = c("ax", "bx", "cx") 
d2 = data.frame(n, s)

rbind(d1, d2)

I'd like to see a new column with "d1" and "d2" as variables. I'm doing it on lots of datasets so eventhough this example is simple the final prdoct will save me a bunch of time. Thx

Jaap
  • 81,064
  • 34
  • 182
  • 193
Dan KS
  • 123
  • 2
  • 13

1 Answers1

0

I believe you're looking for the good ole' deparse(substitute()) trick here. Below i've modified your code to add an additional column to each data.frame that consists of just the name of the data.frame itself.

n = c(2, 3, 5)
s = c("aa", "bb", "cc")
d1 = data.frame(n, s)
d1$name <- deparse(substitute(d1))

n = c(2, 3, 5)
s = c("ax", "bx", "cx")
d2 = data.frame(n, s)
d2$name <- deparse(substitute(d2))

d3 <- rbind(d1, d2)

When you merge them together the resulting data.frame looks like

!> d3
   n  s name
 1 2 aa   d1
 2 3 bb   d1
 3 5 cc   d1
 4 2 ax   d2
 5 3 bx   d2
 6 5 cx   d2
bjoseph
  • 2,116
  • 17
  • 24