Let's say you have two tables of data, maybe imported from separate csv files, and you would like to combine them into one data frame. In this article, we will learn how to combine two data frames in R.
There are two main ways to combine data frames in R. We can use cbind
if we want to combine them side by side, and rbind
if we want to stack them on top of each other.
If you have two data frames that you want to merge based on an Id (such as a user and their purchases), that will be our next article.
Let's see an example of using cbind
to combine side by side.
df1 = data.frame(ads = c("Twitter", "Google"))
df2 = data.frame(sales = c(7000, 8000))
cbind(df1, df2)
# ads sales
# 1 Twitter 7000
# 2 Google 8000
Finally, let's see an example of rbind
to stack two data frames on top of each other.
df1 = data.frame(ads = c("Twitter"), sales = c(7000))
df2 = data.frame(ads = c("Google"), sales = c(8000))
rbind(df1, df2)
# ads sales
# 1 Twitter 7000
# 2 Google 8000