Continuing our discussion on how to merge data frames in R, our attention turns to rbind – the row bind function. Rbind can be used to append two dataframes with the same number of columns together.

We will build on the example we started with cbind, the column bind function. At the end of that session, we had a lovely dataframe which contained manufacturing data for a group of employees. Suppose we were able to find data tracking several additional operators? How would we append this to our existing dataframe? Rbind to the rescue!

### Rbind Example

We are going to pick up with the end of our cbind example:

# data for r rbind example blended <- cbind(blended, sourceofhire) > blended opid units operator found 1 Op01 23 Larry Movie 2 Op02 43 Curly Movie 3 Op03 21 Moe Movie 4 Op04 32 Jack Book 5 Op05 13 Jill Book 6 Op06 12 Kim TV 7 Op07 32 Perry TV

Suppose our IT team realizes that we missed four operators in another building. They send over the information in an email and we can cobble together an appropriate data frame.

# additional rows for r rbind example new <- cbind(opid = c("ex01","ex02","ex03","ex04"), units = c(52,23,32,54), operator = c("nancy", "drew","hardy","boys"), found = c("mystery","mystery","mystery","mystery")) > new opid units operator found 1 Ex01 52 Nancy mystery 2 Ex02 23 Drew mystery 3 Ex03 32 Hardy mystery 4 Ex04 54 Boys mystery

And we can use rbind to join the two.

# rbind in r - combine 2 names to make 1 total <- rbind(blended, new) > total opid units operator found 1 Op01 23 Larry Movie 2 Op02 43 Curly Movie 3 Op03 21 Moe Movie 4 Op04 32 Jack Book 5 Op05 13 Jill Book 6 Op06 12 Kim TV 7 Op07 32 Perry TV 8 Ex01 52 Nancy mystery 9 Ex02 23 Drew mystery 10 Ex03 32 Hardy mystery 11 Ex04 54 Boys mystery

You can also use this to append multiple tables.

# rbind multiple data frames in r total <- rbind(blended, new,new2,new3)

One gotcha. In order to use the rbind function, the two data frames need to have the same number of columns. Otherwise you will get the following lovely error:

> rbind(blended, names) Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match

For more complicated joins, take a look at our article about merging dataframes.