1

I'm rbinding a list (k) of data.frames into a single data.frame (current_output).

But I'm wondering how to add an id column to my resultant data.frame so that I get my desred_output in BASE R?

k = list(A = data.frame(d = 1, n = 2), B = data.frame(d = 1:2, n = 2:3))

current_output = do.call(rbind, k)
#    d n
#A   1 2
#B.1 1 2
#B.2 2 3

desired_ouput1 = data.frame(id = c(1,2,2), d = c(1,1:2), n = c(2,2:3))
#  id d n
#1  1 1 2
#2  2 1 2
#3  2 2 3

desired_ouput2 = data.frame(id = c(A,B,B), d = c(1,1:2), n = c(2,2:3))
#  id d n
#1  A 1 2
#2  B 1 2
#3  B 2 3
rnorouzian
  • 7,397
  • 5
  • 27
  • 72
  • @Henrik, would that be possible to provide a BASE R solution? much appreciated. – rnorouzian Mar 30 '21 at 22:12
  • 1
    See [Combine (rbind) data frames and create column with name of original data frames)](https://stackoverflow.com/questions/15162197/combine-rbind-data-frames-and-create-column-with-name-of-original-data-frames) for several `base` alternatives. – Henrik Mar 30 '21 at 22:13

1 Answers1

4

If you would like to have base R solution, the code below might help you

do.call(
  rbind,
  c(Map(cbind, id = names(k), k),
    make.row.names = FALSE
  )
)

which gives

  id d n
1  A 1 2
2  B 1 2
3  B 2 3

Or you can do

cbind(
  id = rep(
    names(k),
    sapply(k, nrow)
  ),
  do.call(rbind, k)
)

which gives

    id d n
A    A 1 2
B.1  B 1 2
B.2  B 2 3
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81