0

How to add rows from certain column in a data frame to another column of another data frame. See Example below.

> DF1
  A    B  C
1 3  axe aa
2 6 base bb
3 9  lol cc

> DF2
  D  E   
1 x ss 
2 y dd 
3 z vv 

And I want to add/merge the rows of Column E of DF2 into Column C of DF1. And the other columns' rows should be NA.

> DF3
  A    B   C
1 3   axe  aa
2 6   base bb
3 9   lol  cc
4 NA  NA   ss
5 NA  NA   dd
6 NA  NA   vv
Mr. Buster
  • 131
  • 5
  • 1
    Possible duplicate of [How to join (merge) data frames (inner, outer, left, right)?](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) – amrrs Mar 06 '19 at 08:11
  • You can simply use `joining` techniques - with `merge` https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right – amrrs Mar 06 '19 at 08:11

2 Answers2

1

You can rename E to C and rbind. I prefer bind_rows

> library(dplyr)
> names(DF2)[2] <- "C"
> DF1 <- bind_rows(DF1, select(DF2, C))
> DF1
   A    B  C
1  3  axe aa
2  6 base bb
3  9  lol cc
4 NA <NA> ss
5 NA <NA> dd
6 NA <NA> vv

Another approach:

> DF1 %>%
+   bind_rows(DF2) %>%
+   mutate(C = ifelse(is.na(C), E, C)) %>%
+   select(A:C)
   A    B  C
1  3  axe aa
2  6 base bb
3  9  lol cc
4 NA <NA> ss
5 NA <NA> dd
6 NA <NA> vv
Sonny
  • 3,083
  • 1
  • 11
  • 19
0

Use rbind from base R:

DF3 <- rbind(DF1, data.frame(A = NA, B = NA, C = DF2$E))
symbolrush
  • 7,123
  • 1
  • 39
  • 67