【问题标题】:`all observations are in the same group` when `bartlett.test`当 `bartlett.test` 时,`所有观察值都在同一组中`
【发布时间】:2020-08-17 00:28:51
【问题描述】:
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)
}

上面的脚本是一个简单的函数,当我运行它时,出现如下错误:

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

有什么问题??

【问题讨论】:

    标签: r


    【解决方案1】:

    这是一个修改后的版本,它返回两个测试运行的结果。

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

    【讨论】:

    • 我注意到你使用&amp;&amp;而不是&amp;,并且使用df[[col2]]而不是df[,col2]。为什么?
    • @kittygirl 因为&amp; 是向量化的形式,并且该连词的每一侧只有一个元素。见this SO post。还有this one.
    【解决方案2】:

    尝试双括号方法:

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

    然后:

    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
    

    【讨论】:

    • df[,col2]df[[col2]] 有什么区别?据我所知,它们是一回事。
    猜你喜欢
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2018-08-08
    • 2021-05-28
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多