C.Robin
C.Robin

Reputation: 1102

Feed a vector of values into power function

I want to estimate the minimum detectable effect size for various levels of N and SD. Power is always fixed at 0.8 and alpha is always fixed at 0.05.

This is my code so far:

library(pwr)

power_fcn <- function(.x){
  
  power.t.test(n = .x, d = NULL, power = 0.8, sig.level = 0.05, alternative = "two.sided")
  
}

power_df <- 
  map_dfr(
    .x = seq(10000, 30000, by = 5000),
    .f = power_fcn
  )

But the above returns this error:

Error: Argument 1 must be a data frame or a named atomic vector.

but as far as I can see .x is a vector...

What i'd like to be able to produce is something like this:

# A tibble: 5 x 5
      n power sig.level test      cohens_d
  <dbl> <dbl>     <dbl> <chr>        <dbl>
1 10000   0.8      0.05 two-sided   0.0229
2 15000   0.8      0.05 two-sided   0.0323
3 20000   0.8      0.05 two-sided   0.0280
4 25000   0.8      0.05 two-sided   0.0251
5 30000   0.8      0.05 two-sided   0.0229

ideally with options to the function to add another column which converts the cohen's d into the units of the variable I care about (i.e. by passing through the SD).

Upvotes: 1

Views: 164

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389155

You can use the following -

library(dplyr)

power_fcn <- function(.x){
  tmp <- power.t.test(n = .x, d = NULL, power = 0.8, 
                      sig.level = 0.05, alternative = "two.sided")

  tibble(n = .x, power = 0.8, sig.level = 0.05, 
         test = 'two.sided', cohens_d = tmp$delta)
}

sd <- 0.5

purrr::map_dfr(
  .x = seq(10000, 30000, by = 5000),
  .f = power_fcn
) %>%
  mutate(mdes = cohens_d * sd)

#     n power sig.level test      cohens_d   mdes
#  <dbl> <dbl>     <dbl> <chr>        <dbl>  <dbl>
#1 10000   0.8      0.05 two.sided   0.0396 0.0198
#2 15000   0.8      0.05 two.sided   0.0323 0.0162
#3 20000   0.8      0.05 two.sided   0.0280 0.0140
#4 25000   0.8      0.05 two.sided   0.0251 0.0125
#5 30000   0.8      0.05 two.sided   0.0229 0.0114

Upvotes: 2

Related Questions