How To Fix In R: Arguments Imply Differing Number Of Rows - Statology

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 <- c(1, 2, 3, 4, 5, 6) x2 <- c(8, 8, 8, 7, 5) y <- c(9, 11, 12, 13, 14, 16) #attempt to create data frame using vectors as columns df <- data.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 <- c(1, 2, 3, 4, 5, 6) x2 <- c(8, 8, 8, 7, 5) y <- c(9, 11, 12, 13, 14, 16) #pad shortest vector with NA's to have same length as longest vector length(x2) <- length(y) #create data frame using vectors as columns df <- data.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

Từ khóa » C1-8-5-3-30