这个适用于任何数量的Var&Resps:
d <- structure(list(CASENO = 1:5, Var1 = c(1L, 0L, 1L, 1L, 1L), Var2 = c(0L, 0L, 1L, 1L, 0L), Resp1 = c(1L, 0L, 1L, 0L, 1L), Resp2 = c(1L, 0L, 1L, 1L, 0L)), .Names = c("CASENO", "Var1", "Var2", "Resp1", "Resp2"), class = "data.frame", row.names = c(NA, -5L)) m <- as.matrix(d[,-1]) m2 <- t(m) %*% m rnames <- grepl('Resp',rownames((m2))) cnames <- grepl('Var',colnames((m2))) m2[rnames,cnames]
[更新] G.Grothendieck的评论中提供了一个更优雅的版本:
m <- as.matrix(d[,-1]) cn <- colnames(m); crossprod(m[, grep("Resp", cn)], m[, grep("Var", cn)])