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)
}