0

I have two data frames in R. There is not an ID of any sort in DF1 to use to map the rows to - I just need the entire column copied over for a data migration.

DF1 has 1349 named columns, and empty rows. DF2 has 10 named columns and 2990 rows of sample data.

I made a small scale example:

DF1 <- data.frame(matrix(ncol = 10, nrow = 0))
colnames(DF1) <- c('one','two','three','four','five','six','seven','eight','nine','ten')

one <- c(1,54,7,3,6,3)
seven <- c('MLS','Marshall','AAE','JC','AAA','EXE')
DF2 <- data.frame(one,seven)

The column names are the same, but they are not blocked together in DF1 - they are randomly dispersed.

I want to find an efficient way of mapping the 10 columns and all of the rows from DF2 to DF1 without needing to type in each column name, as I will also need to do with with a much larger data frame later.

I expect the rest of the columns in DF1 to be blank/null other than the 'imported' columns from DF2 have been added -- this is okay. Is there an easy way to do this?

Thanks!

emismi95
  • 17
  • 4
  • 1
    You might want `DF1[names(DF2)] <- DF2`, but it's hard to tell without sample data. If that doesn't work and you need more help, please share a small reproducible example with sample input of about 5 rows and 3-4 columns and also the desired output corresponding to the sample input. Then we can test the solution and see that it works. – Gregor Thomas Jan 03 '22 at 15:48
  • Thanks, sorry about the lack of example (private info). I went ahead and added a small one. I think I have actually tried your solution and obtained an error would you know any possible ways to fix this? – emismi95 Jan 03 '22 at 16:03
  • 1: In `[<-.data.frame`(`*tmp*`, names(DF2), value = list(one = c(1, : replacement element 1 has 6 rows to replace 0 rows – emismi95 Jan 03 '22 at 16:04

1 Answers1

2

dplyr has a nice utility for this:

dplyr::bind_rows(DF1, DF2)
#   one two three four five six    seven eight nine ten
# 1   1  NA    NA   NA   NA  NA      MLS    NA   NA  NA
# 2  54  NA    NA   NA   NA  NA Marshall    NA   NA  NA
# 3   7  NA    NA   NA   NA  NA      AAE    NA   NA  NA
# 4   3  NA    NA   NA   NA  NA       JC    NA   NA  NA
# 5   6  NA    NA   NA   NA  NA      AAA    NA   NA  NA
# 6   3  NA    NA   NA   NA  NA      EXE    NA   NA  NA
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 1
    Beat me to it! However, you might need to ensure that `DF1$seven` and `DF2$seven` have compatible datatypes; I got the following error when I tried your code: ```Error: Can't combine `..1$seven` and `..2$seven` ```. – Greg Jan 03 '22 at 16:08