这段代码有很多问题。虽然并不完全清楚代码试图做什么(你应该更清楚地问你的问题),但我相信这会满足你的要求:
for (group.name in Groups) {
g <- get(group.name) # retrieve the actual data
for (i in 1:length(Positive)) {
if (sd(g[[Positive[i]]]) < sdthresh | sd(g[[Negative[i]]]) < sdthresh) {
cat('Standard deviation too low to run\ ',
Positive[[i]], Negative[[i]], '\ comparison')
}
else{
corr<-cor(g[[Positive[i]]], g[[Negative[i]]],use="complete.obs")
print(paste("The correlation between", Positive[[i]],
"and", Negative[[i]], "was", corr, "in", group.name))
}
}
}
例如,当我创建随机数据集(始终提供可重现的示例!)时:
set.seed(1)
bdicontrol = as.data.frame(matrix(rnorm(100), nrow=10))
bdi = as.data.frame(matrix(rnorm(100), nrow=10))
colnames(bdicontrol) <- c(Positive, Negative)
colnames(bdi) <- c(Positive, Negative)
输出是:
[1] "The correlation between PA and NA was -0.613362711250911 in bdicontrol"
[1] "The correlation between Sad_PA and Sad_NA was 0.321335485805636 in bdicontrol"
[1] "The correlation between Amuse_PA and Amuse_NA was 0.0824438791207575 in bdicontrol"
[1] "The correlation between Happy_PA and Happy_NA was -0.192023690189678 in bdicontrol"
[1] "The correlation between Disgust_PA and Disgust_NA was -0.326390681138363 in bdicontrol"
[1] "The correlation between PA and NA was 0.279863504447769 in bdi"
[1] "The correlation between Sad_PA and Sad_NA was 0.115897422274498 in bdi"
[1] "The correlation between Amuse_PA and Amuse_NA was -0.465274556165398 in bdi"
[1] "The correlation between Happy_PA and Happy_NA was 0.268076939911701 in bdi"
[1] "The correlation between Disgust_PA and Disgust_NA was 0.573745174454954 in bdi"