简体   繁体   English

使用 R pwr package 绘制功率与效果大小的关系

[英]Plotting power vs. effect size using R pwr package

I can successfully create plots of power vs. sample size in R using the pwr package.我可以使用 pwr package 在 R 中成功创建功率与样本大小的关系图。 Example code below.下面的示例代码。

library(pwr)
library(tidyverse)

plot.out <- pwr.t2n.test(n1=30, n2=30, d=0.5, alternative="two.sided")

#See output in link below
plot(plot.out)

plot() output情节()output

I would like to create a similar plot -- a two-sample t-test in which effect size is on the y-axis and power is on the x-axis , with fixed sample sizes .我想创建一个类似的 plot -两个样本 t 检验,其中效应大小在 y 轴上,功率在 x 轴上样本大小固定

Is there a way to do this using pwr and/or the plot function?有没有办法使用 pwr 和/或 plot function 来做到这一点? Or would I have to unlist the plot.out object and use it somehow?或者我是否必须取消列出 plot.out object 并以某种方式使用它?

I'm still new to power curves in R.我对 R 中的功率曲线仍然不熟悉。 Thanks in advance for any advice.提前感谢您的任何建议。

In the code below the power is computed in a loop on effect size d_seq .在下面的代码中,功率是在效果大小d_seq的循环中计算的。 Then the power d is extracted from the results list, a data.frame is created and plotted.然后从结果列表中提取幂d ,创建并绘制一个 data.frame。

library(pwr)
library(ggplot2)

d_seq <- seq(0, 2, by = 0.1)
pwr_list <- lapply(d_seq, function(d){
  pwr.t2n.test(n1 = 30, n2 = 30, 
               d = d,
               power = NULL,
               sig.level = 0.05, 
               alternative = "two.sided")
})
pwr <- sapply(pwr_list, '[[', 'power')

dfpwr <- data.frame(power = pwr, effect.size = d_seq)

ggplot(dfpwr, aes(effect.size, power)) +
  geom_point(size = 2, colour = "black") +
  geom_line(size = 0.5, colour = "red") +
  scale_y_continuous(labels = scales::percent) +
  xlab("effect size") +
  ylab(expression("test power =" ~ 1 - beta))

在此处输入图像描述


To draw a line where power is 80% and get the effect size, first compute the effect size from the pwr vector by linear interpolation.要绘制一条功率为 80% 的线并获得效果大小,首先通过线性插值从pwr向量计算效果大小。

pwr80 <- approx(x = pwr, y = d_seq, xout = 0.8)

Now create a label for geom_text and plot it.现在为geom_text和 plot 创建一个 label。

lbl80 <- paste("Power = 80%\n")
lbl80 <- paste(lbl80, "Effect size =", round(pwr80$y, 2))

ggplot(dfpwr, aes(effect.size, power)) +
  geom_point(size = 2, colour = "black") +
  geom_line(size = 0.5, colour = "red") +
  geom_hline(yintercept = 0.8, linetype = "dotted") +
  geom_text(x = pwr80$y, y = pwr80$x, 
            label = lbl80,
            hjust = 1, vjust = -1) +
  scale_y_continuous(labels = scales::percent) +
  xlab("effect size") +
  ylab(expression("test power =" ~ 1 - beta))

在此处输入图像描述

To also draw a vertical line, add要绘制垂直线,请添加

geom_vline(xintercept = pwr80$y, linetype = "dotted")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM