Home > Software design >  R leveneTest group without specific name
R leveneTest group without specific name

Time:05-25

is it possible to use leveneTest without refering to specific column using $. For example, I have a dataset with group in first column and numeric values in second column. I tried to do something like this, but it isn't working.

leveneTest(data[2] ~ data[1], data= data)

I checked that data$group and data[1] has diffrent types, so I think this is causing the problem, but I don't know how to fix this.

CodePudding user response:

The [ returns a data.frame with single column (if there is no comma - for data.frame). Instead we need [[ to extract as vector

leveneTest(data[[2]] ~ data[[1]])

-reproducible example

> library(car)
# using names
> with(Moore, leveneTest(conformity, fcategory))
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  2   0.046 0.9551
# using column index
> leveneTest(Moore[[2]]  ~Moore[[3]])
Levene's Test for Homogeneity of Variance (center = median)
      Df F value Pr(>F)
group  2   0.046 0.9551
      42           
# showing column index, but not extracting as vector    
> leveneTest(Moore[2]  ~Moore[3])
Error in model.frame.default(form) : 
  invalid type (list) for variable 'Moore[2]'

If we look at the structure, it is evident

> str(Moore[[2]])
 int [1:45] 8 4 8 7 10 6 12 4 13 12 ...
> str(Moore[2])
'data.frame':   45 obs. of  1 variable:
 $ conformity: int  8 4 8 7 10 6 12 4 13 12 ...
  • Related