您不需要循環,因此將結果存儲在列表中可能會更加方便。下面是一些假的數據爲例:
frame1 <- data.frame(a1=rnorm(10), a2=rnorm(10), a3=rnorm(10), a4=rnorm(10))
frame2 <- data.frame(b1=rnorm(10), b2=rnorm(10), b3=rnorm(10), b4=rnorm(10))
# setup all column combinations
cols <- expand.grid(1:ncol(frame1), 1:ncol(frame2))
# output to named list
setNames(apply(cols, 1, function(x) {
chisq.test(table(frame1[,x[1]], frame2[,x[2]]))
}), paste(names(frame1)[cols[,1]], names(frame2)[cols[,2]], sep=':'))
結果(第幾個條目):
$`a1:b1`
Pearson's Chi-squared test
data: table(frame1[, x[1]], frame2[, x[2]])
X-squared = 90, df = 81, p-value = 0.2313
$`a2:b1`
Pearson's Chi-squared test
data: table(frame1[, x[1]], frame2[, x[2]])
X-squared = 90, df = 81, p-value = 0.2313
$`a3:b1`
Pearson's Chi-squared test
data: table(frame1[, x[1]], frame2[, x[2]])
X-squared = 90, df = 81, p-value = 0.2313
$`a4:b1`
Pearson's Chi-squared test
data: table(frame1[, x[1]], frame2[, x[2]])
X-squared = 90, df = 81, p-value = 0.2313
$`a1:b2`
Pearson's Chi-squared test
data: table(frame1[, x[1]], frame2[, x[2]])
X-squared = 90, df = 81, p-value = 0.2313
...