## The sample sizes. n = 10 m = 10 ## Generate permutation-test p-values for 1000 null data sets. pv = array(0, 1000) for (j in (1:1000)) { ## Variances for the two populations. V = rexp(2) ## Generate the 'actual' data. X = sqrt(V[1])*rnorm(n) Y = sqrt(V[2])*rnorm(m) ## Calculate the Z-statistic for the actual data. mx = mean(X) my = mean(Y) vx = var(X) vy = var(Y) T = (mx - my) / sqrt(vx/n + vy/n) ## Merge all the data together. Z = c(X, Y) ## Get 1000 Z-statistics for permuted data. TR = array(0, 1000) for (r in (1:1000)) { ## Generate a random permutation. ii = order(runif(m+n)) ## Construct x and y data sets by random reassignment. x = Z[ii[1:n]] y = Z[ii[(n+1):(n+m)]] ## Calculate the Z-statistic for the reassigned data. mx = mean(x) my = mean(y) vx = var(x) vy = var(y) TR[r] = (mx - my) / sqrt(vx/n + vy/n) } ## Two-sided p-value. pv[j] = mean(abs(TR) > abs(T)) }