Adding a one dataframe to the end of another data.frame in R

Sheila picture Sheila · Apr 28, 2012 · Viewed 75.8k times · Source

I'm having difficulty adding one to the bottom of another data frame.

I have one data frame (let's call it DF1) that has 1 row and 5 columns. I have another dataframe (lets call it DF2) that has 50 rows, and 5 columns. I set it up such that the columns between BOTH data frames match - they have the same columns. In fact, DF1 is a calculation based on DF2.

This is what DF1 looks like:

   row.names     pt1     pt2     pt3     pt4
   calc          0.93    0.45    0.28    0.54

This is what DF2 looks like:

   row.names     pt1     pt2     pt3     pt4
   SNP1          AA      AG      AG      AA       
   SNP2          CT      CT      TC      CC
   SNP3          GG      CG      CG     <NA>
   SNP4          AA      GG      AG      AA
   SNP5         <NA>    <NA>    <NA>    <NA>

DF1 is supposed to be the the number of actual data points(# of values that is not missing) divided by the total number of possible values.

SO.. I want to add DF1 to the bottom of DF2 to look like this:

   row.names     pt1     pt2     pt3     pt4
   SNP1          AA      AG      AG      AA       
   SNP2          CT      CT      TC      CC
   SNP3          GG      CG      CG     <NA>
   SNP4          AA      GG      AG      AA
   SNP5         <NA>    <NA>    <NA>    <NA>
   calc          0.93    0.45    0.28    0.54

When I tried using

 both.dfs <- rbind(DF1, DF2)  # DF1 is first here

DF1 is the first row in DF2. I NEED it to be the LAST row.

When I tried using

both.dfs <- rbind(DF2, DF1)  # DF2 is first here

I get an error:

Warning messages:
1: In `[<-.factor`(`*tmp*`, iseq, value = 0.84) :
  invalid factor level, NAs generated
2: In `[<-.factor`(`*tmp*`, iseq, value = 0.84) :
  invalid factor level, NAs generated
3: In `[<-.factor`(`*tmp*`, iseq, value = 0.84) :
  invalid factor level, NAs generated
4: In `[<-.factor`(`*tmp*`, iseq, value = 0.74) :
  invalid factor level, NAs generated

I've tried merge, I've tried adding a new row to DF2 and then subbing in the values of DF2..nothing seems to work! I'm in desperate need of some help! Anyone?

Answer

IRTFM picture IRTFM · Apr 28, 2012

Here's what you should do:

DFtranspose <- cbind(t(DF1[2, ]), t(DF2))
rownames(DFtranspose) <- DF1[1, ]