#Enter the data: #Before: x1 <- c(25, 25, 27, 44, 30, 67, 53, 53, 52, 60,28) #After: x2 <- c(27, 29, 37, 56, 46, 82, 57, 80, 61, 59, 43) #Create the "coin" vector (y=heads, n=tails): xc <- c("y", "n") #Put the data together: a <- as.data.frame(cbind(x1,x2)) #Begin the for loop: avgdif <- rep(0,1000) #Initialize the avgdif. for(i in 1:1000){ xx <- sample(1:11) #Re-randomize the data. q <- sample(xc, 11, replace=TRUE) #Decide the "swap" by tossing a coin. #Place the re-randomized data and the "swap" variable together: aa <- cbind(a[xx,], q) #Identify which pairs to be swaped: ry <- which(aa\$q=="y") #Compute the average difference: avgdif[i] <- (sum(aa[ry,]\$x2-aa[ry,]\$x1)+sum(aa[-ry,]\$x1-aa[-ry,]\$x2)) / 11 } #Construct the histogram of the 1000 average differences: hist(avgdif) #Place the actual difference from the original data: adif <- sum(a\$x1-a\$x2)/11 points(adif, 0, col="green", pch=19) #Count how many simulated average difference values are less than or equal to the observed average difference: sum(avgdif <= adif)