簡體   English   中英

R中的for循環以獲取表格

[英]for loop in R to get a table

我們正在研究我們的論文。 我們想制作一個表格,其中包含一個區域在不同時間段內的相關性和等級相關性的均值、最大值和最小值。 但結果只為我們提供了最后一個時間段的正確數字。 代碼中的EC1是不同時間段的返回,在xts中。

EC_correlation_table <- matrix(nrow=10,ncol=3,byrow=T)
colnames(EC_correlation_table) <-c("Avg","Max","Min")
rownames(EC_correlation_table) <- rep(c("ρ","ρs"),times=5)
        for (a in c("EC1","EC2","EC3","EC4","EC5") ){
    for (i in seq(1,10,2)) {
      EC_correlation_table[i,1]<-mean(cor(get(a)))
      n <- length(cor(get(a)))
      EC_correlation_table[i,2]<-sort(cor(get(a)))[n-length(colnames(EC))]
      EC_correlation_table[i,3]<-min(cor(get(a)))
      
      EC_correlation_table[i+1,1]<-mean(cor(get(a),method = "spearman"))
       n <- length(cor(get(a),method = "spearman"))
      EC_correlation_table[i+1,2]<-sort(cor(get(a),method = "spearman"))[n-length(colnames(EC))]
      EC_correlation_table[i+1,3]<-min(cor(get(a),method = "spearman"))
    }
    }

這是我們得到的結果,但顯然,它只是在最后一個時期重復正確的數字。

 > EC_correlation_table
         Avg       Max       Min
ρ  0.8326252 0.9310787 0.6795128
ρs 0.7920609 0.9139772 0.5997149
ρ  0.8326252 0.9310787 0.6795128
ρs 0.7920609 0.9139772 0.5997149
ρ  0.8326252 0.9310787 0.6795128
ρs 0.7920609 0.9139772 0.5997149
ρ  0.8326252 0.9310787 0.6795128
ρs 0.7920609 0.9139772 0.5997149
ρ  0.8326252 0.9310787 0.6795128
ρs 0.7920609 0.9139772 0.5997149

我認為我們在某些時候犯了一個小錯誤,但就是想不通。

想了一晚上,終於找到了解決辦法~

for (i in 1:5) {
  for (a in sort(c("EC1","EC2","EC3","EC4","EC5"))[i] ){
    b<- 1+seq(0,8,2)[i]
  EC_correlation_table[b,1]<-mean(cor(get(a)))
  n <- length(cor(get(a)))
  EC_correlation_table[b,2]<-sort(cor(get(a)))[n-length(colnames(EC))]
  EC_correlation_table[b,3]<-min(cor(get(a)))
  c<- 1+seq(1,9,2)[i]
  EC_correlation_table[c,1]<-mean(cor(get(a),method = "spearman"))
   n <- length(cor(get(a),method = "spearman"))
  EC_correlation_table[c,2]<-sort(cor(get(a),method = "spearman"))[n-length(colnames(EC))]
  EC_correlation_table[c,3]<-min(cor(get(a),method = "spearman"))
}
}

暫無
暫無

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

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