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

在R中逐行运行power.prop.test并提取结果中的n值添加为新列

解决方案:逐行执行power.prop.test并提取样本量n

嗨,这个需求很清晰,我给你几个实用的解决方案,都是在R里能直接跑的:

首先,先把你的数据加载到环境里:

df <- structure(list(P1 = c(0.02, 0.02, 0.02, 0.02, 0.02, 0.02), 
                     P2 = c(0.022, 0.024, 0.026, 0.028, 0.03, 0.032)), 
                .Names = c("P1", "P2"), row.names = c(NA, 6L), class = "data.frame")

方法1:用dplyr+purrr(简洁高效,推荐)

如果你习惯用tidyverse的工具,这个方法最直观:

library(dplyr)
library(purrr)

# 方式A:rowwise按行处理
df_result <- df %>%
  rowwise() %>%
  mutate(required_n = power.prop.test(p1 = P1, p2 = P2, power = 0.8)$n) %>%
  ungroup()

# 方式B:pmap批量处理(大数据集下效率更高)
df_result <- df %>%
  mutate(required_n = pmap_dbl(., ~ power.prop.test(p1 = ..1, p2 = ..2, power = 0.8)$n))
  • rowwise()会让dplyr逐行处理数据,每一行的P1和P2会传入power.prop.test
  • pmap_dbl则是把每一行的两个参数打包传给函数,直接返回数值结果,适合数据量较大的情况

方法2:基础R的apply函数(无需额外包)

如果不想加载tidyverse,用基础R的apply也能搞定:

df$required_n <- apply(df, 1, function(row_data) {
  power.prop.test(p1 = row_data[1], p2 = row_data[2], power = 0.8)$n
})
  • apply(df, 1, ...)中的1表示按行处理,每一行的数据会作为向量传入匿名函数,然后提取对应位置的P1和P2

方法3:for循环(新手友好,逻辑清晰)

如果你想更清楚看到每一步的执行过程,用for循环也可以:

# 先初始化存储结果的列
df$required_n <- numeric(nrow(df))

for(i in 1:nrow(df)) {
  # 逐行调用检验函数
  test_result <- power.prop.test(p1 = df$P1[i], p2 = df$P2[i], power = 0.8)
  # 提取n值存入新列
  df$required_n[i] <- test_result$n
}

结果示例

运行完上面任意一种方法后,你的数据框会新增一列required_n,存储每组参数对应的样本量(注意:power.prop.test返回的n是每组的样本量,不是总样本量)。输出大概是这样:

P1    P2 required_n
1 0.020 0.022   17719.58
2 0.020 0.024    4429.89
3 0.020 0.026    2013.77
4 0.020 0.028    1179.90
5 0.020 0.030     779.00
6 0.020 0.032     563.76

小提示

  • 如果需要调整显著性水平,可以在power.prop.test里加上alpha参数,比如alpha=0.01
  • 结果里的n是小数,你可以用ceiling()函数把它取整为整数样本量,比如mutate(required_n = ceiling(power.prop.test(...)$n))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:32:02