Fixing R Error Message: number of rows of result is not a multiple of vector length (arg 1)

Error messages are an annoying part of programming, sometimes they are hard to understand, sometimes they are easy in the error message actually means what it says. The “number of rows of result is not a multiple of vector length” error message is a good example of one that actually means what it says.

The circumstances of this error.

This error occurs when using the cbind() function on a set of vectors. It results when there are vectors that are shorter the others.

> x = c(1,2,3,4,5,6,7)
> y = c(1,2,3,4,5,6,7,8)
> z = c(1,2,3,4,5,6,7,8)
> cbind(x,y,z)
x y z
[1,] 1 1 1
[2,] 2 2 2
[3,] 3 3 3
[4,] 4 4 4
[5,] 5 5 5
[6,] 6 6 6
[7,] 7 7 7
[8,] 1 8 8
Warning message:
In cbind(x, y, z) :
number of rows of result is not a multiple of vector length (arg 1)

This code illustrates how this error message occurs, in a simple and straightforward manner.

What is causing this error?

The error is caused by a mismatch in the lengths of the vectors that you are combining. It means that one or more of the vectors is shorter than the others.

> x = c(1,2,3,4,5,6,7)
> y = c(1,2,3,4,5,6,7,8)
> z = c(1,2,3,4,5,6,7,8)

If you look closely at the snippet of code above, you will see that “x” only goes to 7, while “y” and “z” go to 8. This is the key to understanding this error. It simply means that one or more of the vectors is too short.

[6,] 6 6 6
[7,] 7 7 7
[8,] 1 8 8

In the printout of the combination of these three vectors, the first one ends in 1 while the other two end in 8. The result is that it produces the error message. If “x” only had a length of four, you would not get an error message and the vector would just repeat.

How to fix this error.

Fixing this error it’s quite simple, it just requires making sure that all of the factors you are trying to combine have the same length. This is easy to do if you are making up the data but not when working with real-world data.

> x = c(1,2,3,4,5,6,7,0)
> y = c(1,2,3,4,5,6,7,8)
> z = c(1,2,3,4,5,6,7,8)
> data.frame(cbind(x,y,z))
x y z
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 0 8 8

In this particular case, the length of “x” is extended by adding a zero to the end. You can make this extension dynamically with the following bit of code.

x = c(x,0)

You could use a for-loop to extend this approach to any lengths necessary. The key to fixing this error is to find a way to ensure that all of the vectors are the same length. This requirement is true regardless of the approach you may use to reach it.