########################### ### ### Section 5.11 Examples ### ########################### ## Randomization Test with Two Independent Samples withDH <- c(6,2,3,6,8,1,3,7,6,4,4,12,5,6,13,6,9,5,6,7,4,3,2,5,5,6,14,14,7,0) withoutDH <- c(1,5,5,4,7,2,6,2,9,2,8,8,2,10,4,4,3,4,1,9,3,5,1,3,3,3,5,2,7,2) T1.obs <- sum(withDH) combined.sample <- c(withDH, withoutDH) num.perm <- 50000 permutation.matrix <- matrix(0,ncol=length(combined.sample),nrow=num.perm) for (i in 1:num.perm){ # getting random permutation of combined.sample: permutation.matrix[i,] <- sample(combined.sample) } null.T1.distn <- rowSums(permutation.matrix[,(1:length(withDH))]) p.value <- mean(null.T1.distn >= T1.obs) # For an upper-tailed test print(p.value) ## Randomization Test with Two Paired Samples drugA <- c(74,55,61,41,53,74,52,31,50,58,54,53,69,60,61,54,57) drugB <- c(63,58,49,47,50,69,67,40,44,38,56,38,47,41,46,47,44) diffs <- drugA - drugB diffs <- diffs[diffs != 0] # removing any "zero differences" T2.obs <- sum(diffs[diffs>0]) num.perm <- 50000 permutation.matrix <- matrix(0,ncol=length(diffs),nrow=num.perm) for (i in 1:num.perm){ # getting random permutation of signs for vector of differences: permutation.matrix[i,] <- sample(c(-1,1),replace=T,size=length(diffs))*diffs } null.T2.distn <- rowSums(pmax(permutation.matrix,0)) p.value <- 2*min( mean(null.T2.distn >= T2.obs), mean(null.T2.distn <= T2.obs) ) # For a two-tailed test print(p.value)