Skip to content

Instantly share code, notes, and snippets.

@timothyslau
Created August 26, 2015 15:34
Show Gist options
  • Save timothyslau/372554d3d424edd1c2ca to your computer and use it in GitHub Desktop.
Save timothyslau/372554d3d424edd1c2ca to your computer and use it in GitHub Desktop.
A function for computing the within-group sum of cross products (SCPW)
# data from p.645 Explaining Psychological Statistics
dat <- data.frame(initial = c(1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7), final = c(3, 4, 3, 5, 7, 7, 6, 9, 6, 8, 2, 6, 5, 8, 6, 9, 8, 6, 2, 4, 3, 5, 3, 7, 5, 7, 4, 9, 8, 6), condition = factor(x = c(rep(x = "psycho", times = 10), rep(x = "behav", times = 8), rep(x = "cont", times = 12)), levels = c("cont", "behav", "psycho")))
# function
scpw <- function(condition, ){
n <- length(dat[dat$condition == "cont", "initial"]) - 1
sdx <- sd(dat[dat$condition == "cont", "initial"])
sdy <- sd(dat[dat$condition == "cont", "final"])
r <- cor(dat[dat$condition == "cont", "final"], dat[dat$condition == "cont", "initial"])
n * sdx * sdy * r
}
@timothyslau
Copy link
Author

Update1 (I was able to avoid using a for loop; faster):
sum(sapply(X = levels(dat$condition), FUN = function(condition, x = "initial", y = "final"){{
n <- length(dat[dat$condition == condition, x]) - 1
sdx <- sd(dat[dat$condition == condition, x])
sdy <- sd(dat[dat$condition == condition, y])
r <- cor(dat[dat$condition == condition, y], dat[dat$condition == condition, x])
n * sdx * sdy * r
}}))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment