簡體   English   中英

使用兩個for循環在R中定義數據集和變量

[英]Using two for loops to define datasets and variables in R

我需要在一個簡單的循環(如下)中訪問來自兩個不同數據集的變量。 (我意識到這需要負向量和正向量的長度相同...幸運的是,情況總是如此。)

Groups<-c("bdiControl","bdi")
Positive<-c("PA","Sad_PA","Amuse_PA","Happy_PA","Disgust_PA")
Negative<-c("NA","Sad_NA","Amuse_NA","Happy_NA","Disgust_NA")

for (g in Groups) {
    for (i in Positive) { 

if (sd(Groups[[g]]$Positive[[i]])<sdthresh | sd(Groups[[g]]$Negative[[i]]])<sdthresh){
cat('Standard deviation too low to run\ ',Positive[[i]],Negative[[i]],'\ comparison')
}
else{
corr<-cor(Groups[[g]]$Positive[[i]],Groups[[g]]$Negative[[i]],use="complete.obs") 
print("The correlation between " Positive[[i]] " and " Negative[[i]] " was " corr "for " Groups[[g]])
}
}
}

我嘗試過的其他參考包括g $ i,Groups [g] $ Positive [i],g $ Positive [[i]]和類似的排列。 我想我正在解決問題的車輪上旋轉。 救命?! :)

這段代碼有很多問題。 雖然尚不清楚代碼試圖做什么(您應該更清楚地提出問題),但我相信這可以滿足您的要求:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM