Home » How to Fix in R: Arguments imply differing number of rows

How to Fix in R: Arguments imply differing number of rows

by Tutor Aspire

One error you may encounter in R is:

arguments imply differing number of rows: 6, 5

This error occurs when you attempt to create a data frame and the number of rows in each column of the data frame is not the same.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we attempt to create a data frame in R using three vectors:

#define vectors
x1 #attempt to create data frame using vectors as columns
df frame(x1=x1, x2=x2, y=y)

Error in data.frame(x1 = x1, x2 = x2, y = y) : 
  arguments imply differing number of rows: 6, 5

We receive an error because each vector does not have the same length, so each column in the resulting data frame does not have the same number of rows.

We can verify this by printing the length of each vector:

#print length of each vector
length(x1)

[1] 6

length(x2)

[1] 5

length(y)

[1] 6

We can see that the vector x2 has a length of 5, which does not match the length of vectors x1 and y.

How to Fix the Error

To fix this error, we simply need to make sure that each vector has the same length so that each column in the resulting data frame has the same number of rows.

For example, we could pad the shortest vector with NA values so that each vector has the same length:

#define vectors
x1 #pad shortest vector with NA's to have same length as longest vector
length(x2) #create data frame using vectors as columns
df frame(x1=x1, x2=x2, y=y)

#view resulting data frame
df

  x1 x2  y
1  1  8  9
2  2  8 11
3  3  8 12
4  4  7 13
5  5  5 14
6  6 NA 16

Notice that we don’t receive an error because each column in the resulting data frame has the same number of rows.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix in R: argument is not numeric or logical: returning na
How to Fix in R: non-numeric argument to binary operator
How to Fix in R: replacement has length zero

You may also like