Select Page

How to Solve R Error in rbind(deparse.level, …): numbers of columns of arguments do not match

by | Programming, R, Tips

This error occurs if you try to use rbind to row-bind two data frames with mismatching numbers of columns.

We can solve the error by using the bind rows function from the dplyr package.

This tutorial will go through how to solve the error with code examples.


Example: Using rbind()

Consider the following two data frames.

df <- data.frame(x = 1:7, 
y = 11:17,
z = 21:27)

df
 x  y  z
1 1 11 21
2 2 12 22
3 3 13 23
4 4 14 24
5 5 15 25
6 6 16 26
7 7 17 27
df2 <- data.frame(x = 50:55, 
y = 63:68
)
df2
  x  y
1 50 63
2 51 64
3 52 65
4 53 66
5 54 67
6 55 68

The data frames contain different values and have two column names in common. The first data frame has three columns named x, y, and z and the second data frame has two columns x and y.

Let’s try to row bind the two data frames using the rbind() function:

df_bind <- rbind(df, df2)
Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match

The error occurs because the first data frame has three columns and the second data frame has two columns. The rbind() function is only suitable for data frames with the same number of columns.

Solution

We can solve this error by using the bind_rows() function from the dplyr package. First, we need to install and load the dplyr package.

install.packages("dplyr")
library("dplyr")

Next, we will apply the bind_rows function to stack the two data frames.

df_bind <- bind_rows(df, df2)
df_bind
 x  y  z
1   1 11 21
2   2 12 22
3   3 13 23
4   4 14 24
5   5 15 25
6   6 16 26
7   7 17 27
8  50 63 NA
9  51 64 NA
10 52 65 NA
11 53 66 NA
12 54 67 NA
13 55 68 NA

The rbind() function cannot cope with mismatching column names or missing columns, whereas bind_rows() can. If there is a case of a missing column, the bind_rows() function assigns NA to the rows in the data frame where that column is missing.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R related errors, go to the article:

How to Solve R Error in parse(text): unexpected symbol

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!