您可以使用outer
res1 <- outer(colnames(mtcars), colnames(mtcars), FUN= function(x,y) {
sapply(as.list(paste(x,y, sep="~")), function(z) {
form1 <- as.formula(z)
fit <- lm(form1, data=mtcars)
summary(fit)$r.squared})
})
或者expand.grid
indx <- expand.grid(colnames(mtcars), colnames(mtcars), stringsAsFactors=FALSE)
res2 <- sapply(seq_len(nrow(indx)),function(i) {i1 <- indx[i,]
form1 <-as.formula(paste(i1[,1], i1[,2], sep="~"))
fit <- lm(formula=form1, data=mtcars)
summary(fit)$r.squared})
dim(res2) <- c(11,11)
res2[1:3,1:3]
# [,1] [,2] [,3]
#[1,] 0.0000000 0.7261800 0.7183433
#[2,] 0.7261800 0.0000000 0.8136633
#[3,] 0.7183433 0.8136633 0.0000000
identical(res1,res2)
#[1] TRUE