Home > front end >  Move data from small data frame to columns in large dataframe with R
Move data from small data frame to columns in large dataframe with R

Time:01-04

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!

CodePudding user response:

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
  • Related