Skip to content

Instantly share code, notes, and snippets.

@andybega
Last active December 31, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybega/7933764 to your computer and use it in GitHub Desktop.
Save andybega/7933764 to your computer and use it in GitHub Desktop.
For Scott, combinations of vectors that are survey answers.
# Change to your data
data <- data.frame(resp=1:5,
w11=sample(1:5, 5, replace=TRUE),
w12=sample(1:5, 5, replace=TRUE),
w13=sample(1:5, 5, replace=TRUE))
data$LoySum <- apply(data[, c("w11", "w12", "w13")], 1, mean)
# Names of the variables we want to look at
q.names <- c("w11", "w12", "w13")
# List of the k for combinations you want to try
items <- c(2, 3) # c(2:6)
# Actual code
measures <- data.frame(resp=data$resp)
for (k in items) {
combinations <- combn(q.names, k)
cat(paste0("Calculating ", ncol(combinations), " combinations with k=", k, "\n"))
name.list <- NULL
for (i in 1:ncol(combinations)) {
name <- paste(combinations[, i], collapse=".")
name.list <- c(name.list, name)
assign(name, apply(data[, combinations[, i]], 1, mean))
}
obj.list <- lapply(name.list, get)
names(obj.list) <- name.list
res <- do.call(cbind, obj.list)
measures <- cbind(measures, res)
}
#measures
# Find correlations with LoySum
cor2 <- function(item) {
res <- cor(data[, "LoySum"], item)
}
# Combine pairwise correlations with k (number of items that were combined)
cors <- unlist(lapply(measures[, 2:ncol(measures)], cor2))
k <- unlist(lapply(strsplit(names(cors), "[.]"), length))
t(rbind(cors, k))
# Plot
plot(k, cors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment