1
variance_homo<-function(df,col1,col2){
    if (is.numeric(df[,col2]) & nlevels(df[,col1])>2){
    bartlett_res<-bartlett.test(col2~col1,df,na.action=na.omit)
    leven_res<-leveneTest(col2,col1,data=df,na.action=na.omit)
    }
    return(bartlett_res)
}

Above script is a simple function,when I run it ,got error as below:

> variance_homo(iris,'Species','Sepal.Length')
Error in bartlett.test.default("Sepal.Length", "Species") : 
  all observations are in the same group
Called from: bartlett.test.default("Sepal.Length", "Species")

Wha's the problem??

kittygirl
  • 1,831
  • 1
  • 12
  • 28

2 Answers2

1

Try the double bracket approach:

variance_homo<-function(df,col1,col2){
    if (is.numeric(df[[col2]]) & nlevels(df[[col1]])>2){
    bartlett_res <- bartlett.test(df[[col2]]~df[[col1]],df,na.action=na.omit)
    leven_res <- leveneTest(df[[col2]],df[[col1]],data=df,na.action=na.omit)
}
return(bartlett_res)
}

Then:

variance_homo(iris,'Species','Sepal.Length')

    Bartlett test of homogeneity of variances

data:  df[[col2]] by df[[col1]]
Bartlett's K-squared = 16.006, df = 2, p-value = 0.0003345
mysteRious
  • 3,487
  • 2
  • 11
  • 25
1

Here is a revised version that returns the results of both test run.

variance_homo <- function(df, col1, col2){
  if (is.numeric(df[[col2]]) && nlevels(df[[col1]]) >= 2){
    fmla <- paste(col2, col1, sep = '~')
    fmla <- as.formula(fmla)
    bartlett_res <- bartlett.test(fmla, df, na.action = na.omit)
    leven_res <- car::leveneTest(fmla, data = df, na.action = na.omit)
    list(bartlett = bartlett_res, levene = leven_res)
  }else stop('not enough levels.')
}

variance_homo(iris, 'Species', 'Sepal.Length')
Rui Barradas
  • 44,483
  • 8
  • 22
  • 48
  • I noticed you use `&&` instead of `&`,and use `df[[col2]]` instead of `df[,col2]`.Why? – kittygirl May 02 '20 at 15:00
  • @kittygirl Because `&` is the vectorized form and that conjunction has only one element on each side. See [this SO post](https://stackoverflow.com/questions/6558921/boolean-operators-and). And [this one](https://stackoverflow.com/questions/16027840/whats-the-differences-between-and-and-in-r). – Rui Barradas May 02 '20 at 15:12