One warning message you may encounter when using R is:
Warning message: In cbind(A, B, C) : number of rows of result is not a multiple of vector length (arg 1)
This warning usually occurs when you attempt to use the cbind() function to column-bind together vectors of different lengths.
It’s worth noting that this message is simply a warning and your code will still run, but the results you get may be different than you were expecting.
The following example shows how to avoid this warning in practice.
How to Reproduce the Warning
Suppose we use the cbind() function to column-bind together three vectors into a data frame:
#define three vectors with different lengths A = c(4, 2, 3, 6) B = c(9, 1, 8, 7, 0, 7) C = c(3, 5, 3, 3, 6, 4) #column bind three vectors into data frame df <- cbind(A, B, C) #view data frame df Warning message: In cbind(A, B, C) : number of rows of result is not a multiple of vector length (arg 1) A B C [1,] 4 9 3 [2,] 2 1 5 [3,] 3 8 3 [4,] 6 7 3 [5,] 4 0 6 [6,] 2 7 4
The cbind function works with the three vectors, but notice that the values of the first vector simply repeat over and over again.
This is known as “recycling” in R.
How to Avoid the Warning
To avoid the warning altogether, we must make sure that the length of each of the vectors we’re using is the same.
One way to accomplish this is to fill in the missing values in the shorter vector with NA values as follows:
#calculate max length of vectors max_length <- max(length(A), length(B), length(C)) #set length of each vector equal to max length length(A) <- max_length length(B) <- max_length length(C) <- max_length #cbind the three vectors together into a data frame df <- cbind(A, B, C) #view data frame df A B C [1,] 4 9 3 [2,] 2 1 5 [3,] 3 8 3 [4,] 6 7 3 [5,] NA 0 6 [6,] NA 7 4
Notice that we don’t receive any warning message this time and the values of the short vector are simply filled in with NA values to ensure that each of the three vectors we used have equal lengths.
The following tutorials explain how to fix other common errors in R: