If you try to plot two variables and the variables do not have the same length, you will encounter the error: ‘x’ and ‘y’ lengths differ.

You can solve this error by ensuring the variables have the same length or by plotting only up to where the variables are the same length.

This tutorial will go through the error in detail and how to solve it with code examples.


Example

Consider an example where we want to create a scatterplot using two variables.

var1 = c(10, 12, 8, 8, 7)
var2 = c(30, 21, 50, 4, 9, 54, 12)

plot(var1, var2)

Let’s run the code to see what happens:

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

The error occurs because the variables var1 and var2 have differing lengths. We can verify this by using the comparison operator == and the built-in length() function.

length(var1) == length(var2)

If the expression evaluates to TRUE then the vectors are of equal length. Otherwise if the expression evaluates to FALSE, the vectors are not of equal length.

[1] FALSE

The vectors are not of equal length.

Solution #1

We can solve this error by ensuring the vectors are of equal length, either by removing values from the longer vector or adding values to the shorter vector, or both. Let’s look at the revised code:

var1 = c(10, 12, 8, 8, 7, 5, 6)
var2 = c(30, 21, 50, 4, 9, 54, 12)

length(var1) == length(var2)

plot(var1, var2)

We will verify that the vectors are of equal length and plot the scatterplot.

[1] TRUE
Scatterplot of two variables
Scatterplot of two variables

Solution #2

Alternatively, we can create a scatter plot with the values in both vectors only up to the length of the shorter vector. In this example the shorter vector, var1 has five values, whereas var2 has 7. Let’s look at the revised code where we plot the first 5 values of var1 and var2:

var1 = c(10, 12, 8, 8, 7)
var2 = c(30, 21, 50, 4, 9, 54, 12)
plot(var1, var2[1:length(var1)])
Scatterplot of first five values from two variables
Scatterplot of first five values from two variables

Summary

Congratulations on reading to the end of this tutorial! 

For further reading on R related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!