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

Error in rbind(deparse.level, …) : numbers of columns of arguments do not match, this issue happens when you try to row-bind two or more data frames together in R using the rbind() function, but the data frames don’t all have the same number of columns.

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

This guide explains in detail how to resolve this issue. How to Reproduce the Error?

Suppose we have the two R data frames shown below.

Let’s create the first data frame

df1 <- data.frame(x=c(11, 14, 14, 25, 13),
                  y=c(24, 24, 12, 28, 20))
df1
  x  y
1 11 24
2 14 24
3 14 12
4 25 28
5 13 20

Now we can create a second data frame

df2 <- data.frame(x=c(12, 21, 12, 50, 17),
                  y=c(31, 61, 20, 20, 10),
                  z=c(21, 17, 17, 18, 25))
df2
  x  y  z
1 12 31 21
2 21 61 17
3 12 20 17
4 50 20 18
5 17 10 25

Now imagine that we try to row-bind these two data frames into a single data frame using rbind:

Row-binding the two data frames together is being attempted.

rbind(df1, df2)
Error in rbind(deparse.level, ...) :
  numbers of columns of arguments do not match

The two data frames don’t have the same number of columns, thus we get an error.

How to correct the issue?

There are two solutions to this issue:

Approach1: Use rbind on Common Columns

Using the intersect() method to identify the shared column names between the data frames and then row-binding the data frames solely to those columns is one technique to solve this issue.

Find common column names

common <- intersect(colnames(df1), colnames(df2))

Now row-bind only on common column names

df3 <- rbind(df1[common], df2[common])

Now we can view the result

df3
   x  y
1  11 24
2  14 24
3  14 12
4  25 28
5  13 20
6  12 31
7  21 61
8  12 20
9  50 20
10 17 10

Approach 2: Use bind_rows() from dplyr

Using the bind_rows() function from the dplyr package, which automatically fills in NA values for column names that do not match, is another way to solve this issue:

library(dplyr)

Let’s bind together the two data frames

df3 <- bind_rows(df1, df2)

Let’s view the result

df3
   x  y  z
1  11 24 NA
2  14 24 NA
3  14 12 NA
4  25 28 NA
5  13 20 NA
6  12 31 21
7  21 61 17
8  12 20 17
9  50 20 18
10 17 10 25

Due to the absence of column z in this data frame, NA values have been filled in for the values from df1.

You may also like...

Leave a Reply

Your email address will not be published.