Home > Back-end >  R - levene Test - Error in complete.cases(y, group) : not all arguments have the same length
R - levene Test - Error in complete.cases(y, group) : not all arguments have the same length

Time:04-24

It is returning an error message when I use my code for Levene Test on R, as below:

z <- leveneTest(week1,week2, center=mean)

And it appears the following error:

Error in complete.cases(y, group) :
not all arguments have the same length

Does anybody know how to solve it?

CodePudding user response:

Although we don't have your data, we can replicate the error quite easily if week1 and week2 are different lengths. We can also infer from the names of the variables that they are two vectors containing data for two different weeks, and from the fact that you are carrying out a Levene test that you wish to compare their variances.

Let's set up some data that has these features and test it out:

set.seed(1)

week1 <- rnorm(10, 6, 1)
week2 <- rnorm(12, 6, 5)

Now let's see if we can replicate your error:

library(car)
#> Loading required package: carData

leveneTest(week1, week2, center = mean)
#> Warning in leveneTest.default(week1, week2, center = mean): week2 coerced to
#> factor.
#> Error in complete.cases(y, group): not all arguments have the same length

Yes - we get the same error (plus a warning). The reason for this is that this is not how you use the leveneTest function. The data needs to be in long format; that is, it wants your first vector to be all the values from week1 and week2 and the second argument to be a grouping variable telling it which week the values came from. In other words, we can test for a difference between the variances of the two vectors by doing

leveneTest(y = c(week1, week2),
           group = factor(c(rep("week1", length(week1)), 
                            rep("week2", length(week2)))),
           center = mean)
#> Levene's Test for Homogeneity of Variance (center = mean)
#>       Df F value  Pr(>F)  
#> group  1  7.8927 0.01083 *
#>       20                  
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Created on 2022-04-23 by the reprex package (v2.0.1)

  • Related