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.
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.
Following this link and wikipedia, Cohen's d for a t-test seems to be:
Where sigma
(denominator) is:
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
}
> res <- cohens_d(x, y)
> res
# [1] 0.5199662
There are several packages providing a function for computing Cohen's d. You can for example use the cohensD
function form the lsr
package :
library(lsr)
set.seed(45)
x <- rnorm(10, 10, 1)
y <- rnorm(10, 5, 5)
cohensD(x,y)
# [1] 0.5199662
Another option is to use the effsize package.
library(effsize)
set.seed(45) x <- rnorm(10, 10, 1)
y <- rnorm(10, 5, 5)
cohen.d(x,y)
# Cohen's d
# d estimate: 0.5199662 (medium)
# 95 percent confidence interval:
# inf sup
# -0.4353393 1.4752717
Another, more recent option is to use effectsize
, which is very flexible and also returns confidence intervals:
https://easystats.github.io/effectsize/reference/cohens_d.html
library(effectsize)
x <- rnorm(10, 10, 1)
y <- rnorm(10, 5, 5)
# for independent measures design
cohens_d(x, y)
#> Cohen's d | 95% CI
#> -------------------------
#> 0.77 | [-0.15, 1.67]
#>
#> - Estimated using pooled SD.
# in case design is paired
cohens_d(x, y, paired = TRUE)
#> Cohen's d | 95% CI
#> -------------------------
#> 0.49 | [-0.19, 1.20]
Created on 2021-06-29 by the reprex package (v2.0.0)