如何在R中循环执行chisq.test并保存各检验的p值?
批量执行卡方检验的R代码修正
核心问题分析
你的代码存在三个关键错误:
- 变量列表错误使用
survey$health这类带数据框前缀的字符串,chisq.test需要的是数值向量而非字符串; - 循环中直接传递字符串给
chisq.test无法识别,需正确提取数据框中的对应变量; - 结果矩阵赋值逻辑错误,每次循环都覆盖了整列数据,而非当前行。
修正后的代码
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("health", "happiness") nLoops <- length(variables) # 用数据框存储结果,比矩阵更直观易读 result <- data.frame( variable = character(nLoops), p_value = numeric(nLoops), stringsAsFactors = FALSE ) for (i in 1:nLoops){ # 用[[ ]]提取数据框中对应名称的变量 test <- chisq.test(survey[[variables[i]]], survey$sex) # 给当前行赋值,避免覆盖所有结果 result[i, "variable"] <- variables[i] result[i, "p_value"] <- test$p.value } # 查看结果 print(result)
拓展:处理多数据框的情况
如果变量分散在不同数据框中,可以用列表存储数据框和变量名的对应关系:
# 定义包含数据框和变量名的列表 var_list <- list( list(df = survey, var = "health"), list(df = survey, var = "happiness") ) result <- data.frame( variable = character(length(var_list)), p_value = numeric(length(var_list)), stringsAsFactors = FALSE ) for (i in seq_along(var_list)){ current_df <- var_list[[i]]$df current_var <- var_list[[i]]$var test <- chisq.test(current_df[[current_var]], current_df$sex) result[i, "variable"] <- current_var result[i, "p_value"] <- test$p.value }
内容的提问来源于stack exchange,提问作者MalinU
相关产品推荐
相关产品推荐

