You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中对多变量进行卡方检验并将结果整理为数据框?

问题描述

我是R和数据分析领域的新手,手头有一份包含两部分的数据集:

  • 20个采用5级Likert量表作答的问题
  • 8个社会人口学变量

以下是数据集的精简示例(仅包含3个问题和3个社会人口学变量):

data.frame(Q1 = c(1, 2, 2, 1, 3, 4, 3, 5, 2, 2),
           Q2 = c(2, 3, 5, 5, 4, 5, 1, 1, 5, 3),
           Q3 = c(4, 4, 2, 3, 2, 1, 1, 1, 5, 5), 
           ageRange = c(2, 3, 1, 1, 3, 4, 4, 2, 1, 1),
           education = c(1, 1, 3, 4, 6, 5, 3, 2, 1, 4),
           maritalStatus = c(1, 0, 0, 0, 0, 1, 1, 0, 0, 1))

需要完成两项任务:

  1. 对每个问题与所有社会人口学变量进行卡方检验,共需得到9组卡方检验结果(Q1-ageRange、Q1-education、Q1-maritalStatus等)
  2. 将这些卡方检验的结果(p值)整理为一个数据框,其中列为3个社会人口学因素,行为3个问题,结构如下:
data.frame(Age = c(0, 0, 0),
           Education = c(0, 0, 0), 
           Married = c(0, 0, 0), row.names = c("Q1", "Q2", "Q3")) 

我尝试使用apply系列函数,但未能成功实现需求。

解决方案

步骤1:加载并拆分数据

先把示例数据加载到环境中,再拆分出问题变量和社会人口学变量:

# 加载示例数据
df <- data.frame(Q1 = c(1, 2, 2, 1, 3, 4, 3, 5, 2, 2),
                 Q2 = c(2, 3, 5, 5, 4, 5, 1, 1, 5, 3),
                 Q3 = c(4, 4, 2, 3, 2, 1, 1, 1, 5, 5), 
                 ageRange = c(2, 3, 1, 1, 3, 4, 4, 2, 1, 1),
                 education = c(1, 1, 3, 4, 6, 5, 3, 2, 1, 4),
                 maritalStatus = c(1, 0, 0, 0, 0, 1, 1, 0, 0, 1))

# 拆分问题列(Q开头)和人口学变量列
question_cols <- grep("^Q", names(df), value = TRUE)
demo_cols <- setdiff(names(df), question_cols)

步骤2:批量执行卡方检验并提取p值

定义一个函数来执行单组卡方检验并返回p值,再用outer函数批量处理所有变量组合:

# 定义卡方检验函数,返回p值
get_chisq_p <- function(q_col, demo_col) {
  tab <- table(df[[q_col]], df[[demo_col]])
  # 执行卡方检验,若存在期望频数过小的情况,可替换为fisher.test(tab)$p.value
  chisq_result <- chisq.test(tab)
  return(chisq_result$p.value)
}

# 生成所有变量组合的p值矩阵
p_matrix <- outer(question_cols, demo_cols, Vectorize(get_chisq_p))

步骤3:转换为目标格式的数据框

把生成的p值矩阵转换成要求的结构:

# 转换为数据框并调整命名
result_df <- as.data.frame(p_matrix)
names(result_df) <- c("Age", "Education", "Married")
row.names(result_df) <- question_cols

# 查看最终结果
print(result_df)

内容的提问来源于stack exchange,提问作者DavidQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:05:37