-2

I would like to combine two data frames horizontally in R.

These are my two data frames:

dataframe 1:

veg     loc    quantity 

carrot  sak    three
pepper  lon    two
tomato  apw    five

dataframe 2:

seller   quantity  veg

Ben      eleven    eggplant  
Nour     six       potato
Loni     four      zucchini
Ahmed    two       broccoli

I want the outcome to be one data frame that looks like this:

veg       quantity

carrot    three
pepper    two
tomato    five
eggplant  eleven
potato    six
zucchini  four
broccoli  two
frodo
  • 1
  • 1
  • 3
  • 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) – massisenergy Jul 16 '19 at 21:05
  • 4
    Select the columns you want from the two data frames, then `rbind` them together – camille Jul 16 '19 at 21:08

2 Answers2

5

The question says "horizontally" but from the sample output it seems that what you meant was "vertically".

Now, assuming the input shown reproducibly in the Note at the end, rbind them like this. No packages are used and no objects are overwritten.

sel <- c("veg", "quantity")
rbind( df1[sel], df2[sel] )

If you like you could replace the first line of code with the following which picks out the common columns giving the same result for sel.

sel <- intersect(names(df1), names(df2))

Note

Lines1 <- "veg     loc    quantity 
carrot  sak    three
pepper  lon    two
tomato  apw    five"

Lines2 <- "seller   quantity  veg
Ben      eleven    eggplant  
Nour     six       potato
Loni     four      zucchini
Ahmed    two       broccoli"

df1 <- read.table(text = Lines1, header = TRUE, strip.white = TRUE)
df2 <- read.table(text = Lines2, header = TRUE, strip.white = TRUE)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

You can do it like this:

library (tidyverse)

df1 <- df1%>%select(veg, quantity)
df2 <- df2%>%select(veg, quantity)

df3 <- rbind(df1, df2)

aaumai
  • 263
  • 1
  • 7