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

R中对dataframe每行执行two-proportions z-test并生成p值列的实现方法

问题原因

你当前的代码将x1、x2整列拼接为一个长向量,n1、n2同理,相当于对全部数据仅执行1次检验,因此只会输出1个结果。要实现逐行执行双比例z检验,需要遍历每行数据单独调用prop.test函数。

实现方案

方法1:基础R实现(无需额外安装包)

直接用apply逐行遍历需要用到的4个字段,提取每次检验的p值存入新列:

df$p_value <- apply(df[, c("x1", "x2", "n1", "n2")], 1, function(row) {
  # 若不需要连续性校正,可添加参数 correct = FALSE
  prop.test(x = c(row["x1"], row["x2"]), n = c(row["n1"], row["n2"]))$p.value
})

方法2:tidyverse生态实现(代码更易读,可扩展提取更多检验结果)

借助purrr包的逐行映射功能实现,若需要同时提取检验统计量、置信区间等其他结果,可搭配broom包使用:

library(tidyverse)

# 仅提取p值
df <- df %>%
  mutate(p_value = pmap_dbl(list(x1, x2, n1, n2), 
                            ~ prop.test(x = c(..1, ..2), n = c(..3, ..4))$p.value))

# 如需提取全部检验结果(统计量、置信区间、p值等)
df <- df %>%
  mutate(test_res = pmap(list(x1, x2, n1, n2), 
                         ~ broom::tidy(prop.test(x = c(..1, ..2), n = c(..3, ..4))))) %>%
  unnest(test_res)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:54:04