我有两个数据帧(比如frame1和frame2)。每个变量都有大量变量(例如,frame1有变量a1,a2,a3 ......而帧2有变量b1,b2,b3 ......)。我正在对来自两个帧的所有可能的变量对进行卡方检验(所以在a1和b1之间; a1和b2; a1和b3,...等等)。我正在使用以下for循环来完成这项工作,完美地解决了输出所有我得到的结果,而没有指定哪个分析属于哪些变量集。我想以某种方式得到结果,以便每个INDIVIDUAL分析前面都有分析所用的两个变量名。
for (i in frame1) {
for (j in frame2)
print({chisq.test(table(i,j))})}
R对我来说很新,所以任何帮助都会受到赞赏!!
答案 0 :(得分:2)
您不需要为此循环,将结果存储在列表中可能会更方便。这是一个假数据的例子:
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
...
答案 1 :(得分:1)
你能做这样的事吗?
for (i in 1:ncol(frame1)) {
for (j in 1:ncol(frame2)) {
print(colnames(frame1)[i])
print(colnames(frame2)[j])
print({chisq.test(table(frame1[,i],frame2[,j]))})
}
}