rstatistics

Estimate Cohen's d for effect size


given two vectors:

x <- rnorm(10, 10, 1)
y <- rnorm(10, 5, 5)

How to calculate Cohen's d for effect size?

For example, I want to use the pwr package to estimate the power of a t-test with unequal variances and it requires Cohen's d.


Solution

  • Following this link and wikipedia, Cohen's d for a t-test seems to be:

    enter image description here

    Where sigma (denominator) is:

    enter image description here

    So, with your data:

    set.seed(45)                        ## be reproducible 
    x <- rnorm(10, 10, 1)                
    y <- rnorm(10, 5, 5)
    
    cohens_d <- function(x, y) {
      lx <- length(x) - 1
      ly <- length(y) - 1
      md <- abs(mean(x) - mean(y))        ## mean difference (numerator)
      csd <- lx*var(x) + ly*var(y)
      csd <- csd/(lx + ly)
      csd <- sqrt(csd)                     ## common sd computation
      cd <- md/csd                        ## cohen's d
      return(cd)
    }
    
    > res <- cohens_d(x, y)
    > res
    # [1] 0.5199662