循环 chisq.test RStudio

问题描述 投票:0回答:1

我正在尝试对大约 30 个变量进行卡方检验。我尝试编写一个 for 循环,但没有成功。循环还应该保存每个测试的 p 值。

我之前在其他情况下使用过这种设置,但我认识到使用带有 dataframe$ 变量名称的向量在这种情况下不起作用。我怀疑从文本到变量名的翻译有一些基本的东西我不明白。

示例:

survey <- data.frame(
  sex = c(1, 2, 2, 1, 1, 2, 1, 1, 2, 1),
  health = c(1, 2, 3, 4, 5, 1, 3, 2, 4, 5),
  happiness = c(1, 3, 4, 5, 1, 2, 4, 2, 3, 5)
)

variables <- c("survey$health", "data$happiness")
nLoops <- length(variables)

result <- matrix(nrow = nLoops, ncol = 2)

for (i in 1:nLoops){
  test <- chisq.test(variables[i], survey$sex)
  result[, 1] <- test$data.name
  result[, 2] <- test$p.value
}
r survey
1个回答
0
投票

基本 R 解决方案,将 for 循环更改为

lapply
调用:

lapply (
  c("health", "happiness"),
  function(var) {
    test <- chisq.test(survey[[var]], survey$sex)
    c("name" = paste(var, "vs sex"), "p.val" = test$p.value)
  }
) 
[[1]]
               name               p.val 
    "health vs sex" "0.796763382262977" 

[[2]]
               name               p.val 
 "happiness vs sex" "0.211945584372718" 
Warning messages:
1: In chisq.test(survey[[var]], survey$sex) :
  Chi-squared approximation may be incorrect
2: In chisq.test(survey[[var]], survey$sex) :
  Chi-squared approximation may be incorrect

警告消息是由于样本量太小而引起的。

© www.soinside.com 2019 - 2024. All rights reserved.