Skip to content

Commit 32b5b2a

Browse files
committedMay 6, 2015
initial commit
1 parent 4063f6e commit 32b5b2a

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
 

‎Ch10 Power analysis.R

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#----------------------------------------#
2+
# R in Action (2nd ed): Chapter 10 #
3+
# Power analysis #
4+
# requires packages pwr to be installed #
5+
# install.packages("pwr") #
6+
#----------------------------------------#
7+
8+
par(ask=TRUE)
9+
10+
library(pwr)
11+
12+
# t tests
13+
pwr.t.test(d=.8, sig.level=.05,power=.9, type="two.sample",
14+
alternative="two.sided")
15+
pwr.t.test(n=20, d=.5, sig.level=.01, type="two.sample",
16+
alternative="two.sided")
17+
18+
19+
# ANOVA
20+
pwr.anova.test(k=5,f=.25,sig.level=.05,power=.8)
21+
22+
# Correlations
23+
pwr.r.test(r=.25, sig.level=.05, power=.90, alternative="greater")
24+
25+
# Linear Models
26+
pwr.f2.test(u=3, f2=0.0769, sig.level=0.05, power=0.90)
27+
28+
# Tests of proportions
29+
pwr.2p.test(h=ES.h(.65, .6), sig.level=.05, power=.9,
30+
alternative="greater")
31+
32+
# Chi-square tests
33+
prob <- matrix(c(.42, .28, .03, .07, .10, .10), byrow=TRUE, nrow=3)
34+
ES.w2(prob)
35+
pwr.chisq.test(w=.1853, df=3 , sig.level=.05, power=.9)
36+
37+
38+
# Listing 10.1 - Sample sizes for detecting significant effects in a One-Way ANOVA
39+
es <- seq(.1, .5, .01)
40+
nes <- length(es)
41+
samsize <- NULL
42+
for (i in 1:nes){
43+
result <- pwr.anova.test(k=5, f=es[i], sig.level=.05, power=.9)
44+
samsize[i] <- ceiling(result$n)
45+
}
46+
plot(samsize,es, type="l", lwd=2, col="red",
47+
ylab="Effect Size",
48+
xlab="Sample Size (per cell)",
49+
main="One Way ANOVA with Power=.90 and Alpha=.05")
50+
51+
52+
# Listing 10.2 - Sample size curves for dtecting corelations of various sizes
53+
library(pwr)
54+
r <- seq(.1,.5,.01)
55+
nr <- length(r)
56+
p <- seq(.4,.9,.1)
57+
np <- length(p)
58+
samsize <- array(numeric(nr*np), dim=c(nr,np))
59+
for (i in 1:np){
60+
for (j in 1:nr){
61+
result <- pwr.r.test(n = NULL, r = r[j],
62+
sig.level = .05, power = p[i],
63+
alternative = "two.sided")
64+
samsize[j,i] <- ceiling(result$n)
65+
}
66+
}
67+
xrange <- range(r)
68+
yrange <- round(range(samsize))
69+
colors <- rainbow(length(p))
70+
plot(xrange, yrange, type="n",
71+
xlab="Correlation Coefficient (r)",
72+
ylab="Sample Size (n)" )
73+
for (i in 1:np){
74+
lines(r, samsize[,i], type="l", lwd=2, col=colors[i])
75+
}
76+
abline(v=0, h=seq(0,yrange[2],50), lty=2, col="grey89")
77+
abline(h=0, v=seq(xrange[1],xrange[2],.02), lty=2, col="gray89")
78+
title("Sample Size Estimation for Correlation Studies\n
79+
Sig=0.05 (Two-tailed)")
80+
legend("topright", title="Power", as.character(p),
81+
fill=colors)
82+

0 commit comments

Comments
 (0)