MM1
MM1

Reputation: 506

Putting a levene test and two-way ANOVA into a user-define function in R

I have been trying to make a custom/user-defined function to perform a levene test and a two-way ANOVA. I am struggling to make the formula factors unique in the {aruguments} in the function. After looking at this post: Error: Custom function that has ~ (tilde) and/or $ (dollar sign) in the body in r I have created the following. However, it is not working.

test_levene <- function(df, contvar, catvar, catvar2){
  contvar <- as.character(substitute(contvar))
  catvar <- as.character(substitute(catvar))
  catvar2 <- as.character(substitute(catvar2))
  fmla <- as.formula(contvar ~ catvar*catvar2)
  require(car)
levene <- leveneTest(fmla,data=df)
pvalue <- levene[[3]][1]
}
#Produces the error: Error in leveneTest.default(y = y, group = group, ...) : 
  y is not a numeric variable

The mentioned post uses reformulate but that keeps making problems/errors. Is there a benefit to using reformulate over as.factor? What is the difference between the two.

Similarly with the two-way ANOVA, this is the structure I would like. How can I make this work!

test_twoway <- function(df, contvar, catvar, catvar2) {
     twoway <- aov(contvar ~ catvar * catvar2, data = df)
     twoway <- summary(twoway)
     ph1 <- TukeyHSD(twoway, catvar)
     ph2 <- TukeyHSD(twoway, catvar2)
}

Upvotes: 3

Views: 125

Answers (1)

I_O
I_O

Reputation: 6921

One approach, perhaps not idiomatic:

test_levene <- function(df, contvar, catvar, catvar2){
  contvar = as.character(substitute(contvar))
  catvar = as.character(substitute(catvar))
  catvar2 = as.character(substitute(catvar2))
  fmla = as.formula(paste(contvar, "~", catvar, "*", catvar2))
  test_result = leveneTest(fmla, data = df)
  ## do something with test result
  test_result
}

(note the use of paste)

> iris$Color <- gl(3, 50, labels = c('blue', 'violet', 'darkblue'))
> test_levene(df = iris, Sepal.Length, Species, Color)
Levene's Test for Homogeneity of Variance (center = median)
       Df F value   Pr(>F)   
group   2  6.3527 0.002259 **
      147                    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Upvotes: 1

Related Questions