Home » How to Fix: error in xy.coords(x, y, xlabel, ylabel, log) : ‘x’ and ‘y’ lengths differ

How to Fix: error in xy.coords(x, y, xlabel, ylabel, log) : ‘x’ and ‘y’ lengths differ

by Tutor Aspire

One common error you may encounter in R is:

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' and 'y' lengths differ 

This error occurs when you attempt to create a plot of two variables but the variables don’t have the same length.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we attempt to create a scatterplot of the following two variables in R:

#define x and y variables
x #attempt to create scatterplot of x vs. y
plot(x, y)

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' and 'y' lengths differ

We receive an error because the length of x and y are not equal.

We can confirm this by printing the length of each variable:

#print length of x
length(x)

[1] 4

#print length of y
length(y)

[1] 6

#check if length of x and y are equal
length(x) == length(y)

[1] FALSE

How to Fix the Error

The easiest way to fix this error is to simply make sure that both vectors have the same length:

#define x and y variables to have same length
x #confirm that x and y are the same length
length(x) == length(y)

[1] TRUE

create scatterplot of x vs. y
plot(x, y)

If one vector happens to be shorter than the other, you could choose to plot only the values up to the length of the shorter vector.

For example, if vector x has 4 values and vector y has 6 values, we could create a scatterplot using only the first 4 values of each vector:

#define x and y variables
x #create scatterplot of first 4 pairwise values of x vs. y
plot(x, y[1:length(x)])

Notice that only the first four values of each vector are used to create the scatterplot.

Additional Resources

How to Fix in R: NAs Introduced by Coercion
How to Fix in R: Subscript out of bounds
How to Fix: longer object length is not a multiple of shorter object length

You may also like