【问题标题】:chisquare test in r that keeps row namesr中的卡方测试,保留行名
【发布时间】:2020-06-04 01:52:19
【问题描述】:

我正在构建包含两个波次的员工调查,并且我想确保每个波次在某些人口统计变量(例如种族和性别)方面保持平衡。这是一个虚构的数据样本:

library(tidyverse)
sample_data <- tibble(demographics = c("White / Female", "Non-White / Female", "White / Male", "Non-White / Male", "White / Transgender", "Non-White / Transgender"),
                      wave_1 = c(40, 38, 60, 56, 0, 2),
                      wave_2 = c(38, 39, 62, 58, 1, 0))

如果我在 sample_data 上运行 chisq.test(),我会得到一个错误:

library(stats)
chisq.test(sample_data)

Error in chisq.test(sample_data) : 
  all entries of 'x' must be nonnegative and finite

但如果我只使用两个计数列,我不会收到错误:

sample_data_count <- sample_data %>%
  dplyr::select(wave_1, wave_2)
chisq.test(sample_data_count)

    Pearson's Chi-squared test

data:  sample_data_count
X-squared = 3.1221, df = 5, p-value = 0.6812

Warning message:
In chisq.test(sample_data_count) :
  Chi-squared approximation may be incorrect

我知道 R 不喜欢我在 sample_data 中包含我的人口统计数据,但是如果我想查看各种人口统计数据的观察值,很难将它们包含在其中。有没有办法使用这些行名运行卡方检验?

我在http://www.sthda.com/english/wiki/chi-square-test-of-independence-in-r 看到了一个使用此数据集 (file_path http://www.sthda.com/sthda/RDoc/data/housetasks.txt") 的示例,确实在 r 中进行卡方检验,其中行名仍在其中。

任何帮助将不胜感激!

【问题讨论】:

    标签: r matrix statistics chi-squared rowname


    【解决方案1】:

    因为它还包含character 列。根据?chisq.test

    x - 数值向量或矩阵。 x 和 y 也可以都是因子。

    y - 一个数字向量;如果 x 是矩阵,则忽略。如果 x 是一个因子,则 y 应该是一个相同长度的因子。

    如果我们想通过numericmatrixselect 数字列或将“人口统计”转换为行名,转换为matrix 并应用测试

    library(dplyr)
    library(tibble)
    sample_data %>% 
       column_to_rownames('demographics') %>%
       as.matrix %>% 
       chisq.test
    

    【讨论】:

      【解决方案2】:

      您可以定义自己的函数,仅在数字列上运行卡方:

       my_chi <- function(df) chisq.test(as.matrix(df[, sapply(df, is.numeric)]))
      

      所以现在你可以做

      my_chi(sample_data)
      #> 
      #>  Pearson's Chi-squared test
      #> 
      #> data:  as.matrix(df[, sapply(df, is.numeric)])
      #> X-squared = 3.1221, df = 5, p-value = 0.6812
      #> 
      #> Warning message:
      #> In chisq.test(as.matrix(df[, sapply(df, is.numeric)])) :
      #>   Chi-squared approximation may be incorrect
      

      【讨论】:

        猜你喜欢
        • 2016-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-27
        • 1970-01-01
        相关资源
        最近更新 更多