:FAQ/medianCI - CBU statistics Wiki
Self: :FAQ/medianCI

Example R code for computing 95% CI for a median

Data is in long format here (each row represents a single occasion on a subject) in a SPSS file called oxigen.sav with columns labeled id (subject identifier), occasion (five occasions), Condition (2 of these) and BADS and PITPV representing the two response variables. We wish to compare 95% confidence intervals for the medians of the representing the differences in a response between a later time point and baseline in each of the two conditions. Since these confidence intervals are based on percentiles these confidence intervals should be more robust to outliers than those using means and variances.

library(foreign)
x <- read.spss("U://My Documents//oxigen.sav")
attach(x)

# CHANGE THE VARIABLE OF INTEREST HERE
a <- PITPV

#a <- BADS
a[a == 999] <- NA 
b <- a[seq(1, length(a), 5)]
# c <-  a[seq(3, length(a), 5)] CHANGE HERE FOR OCCASION TO DIFFERENCE FROM BASELINE E.G. OCCASION 2 AS HERE
c <-  a[seq(2, length(a), 5)] 
diff <- b-c
cond <- Condition[seq(1,length(Condition),5)]
diffnm <- diff[!is.na(diff)]  
cond2 <- cond[!is.na(diff)]

diff2 <- diffnm[cond2==1]
diff3 <- diffnm[cond2==2]

pp2 <-  ( length(diff2)/2 - 1.96*sqrt(length(diff2)/4) ) / length(diff2)
pp3 <- ( length(diff2)/2 + 1.96*sqrt(length(diff2)/4) + 1 ) / length(diff2)

quantile(diff2, c(pp2, pp3))

pp2 <-  ( length(diff3)/2 - 1.96*sqrt(length(diff3)/4) ) / length(diff3)
pp3 <- ( length(diff3)/2 + 1.96*sqrt(length(diff3)/4) + 1 ) / length(diff3)

quantile(diff3, c(pp2, pp3))

None: :FAQ/medianCI (last edited 2013-12-03 12:10:24 by PeterWatson)