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 amount of columns.

R Percentage by Group Calculation – Data Science Tutorials

This guide explains in detail how to resolve this issue.

How to reproduce the Error in rbind(deparse.level …) numbers of columns of arguments do not match?

Suppose we have the two R data frames shown below:

First will create a data frame

df1 <- data.frame(x=c(11, 14, 14, 15, 23),
                  y=c(84, 94, 72, 98, 120))
df1
  x   y
1 11  84
2 14  94
3 14  72
4 15  98
5 23 120

Now we  can create a second data frame

How to Add a caption to ggplot2 Plots in R? (datasciencetut.com)

df2 <- data.frame(x=c(22, 22, 32, 35, 37),
                  y=c(33, 62, 52, 10, 10),
                  z=c(22, 37, 47, 58, 85))
df2
   x  y  z
1 22 33 22
2 22 62 37
3 32 52 47
4 35 10 58
5 37 10 85

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

Let’s try to row-bind the two data frames together

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.

Replace NA with Zero in R – Data Science Tutorials

How to correct the issue

There are two solutions to this issue:

Method 1: Using 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.

Now we can find the common column names

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

Let’s row-bind only on common column names

Separate a data frame column into multiple columns-tidyr Part3

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

Let’s view the result

df3
   x   y
1  11  84
2  14  94
3  14  72
4  15  98
5  23 120
6  22  33
7  22  62
8  32  52
9  35  10
10 37  10

Method 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 both data frames

df3 <- bind_rows(df1, df2) 

Now we can view the result

df3
   x   y  z
1  11  84 NA
2  14  94 NA
3  14  72 NA
4  15  98 NA
5  23 120 NA
6  22  33 22
7  22  62 37
8  32  52 47
9  35  10 58
10 37  10 85

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. Required fields are marked *

five × four =