2014-07-08 17 views
2

我嘗試做以下的子集循環:如何使用「爲」與洗牌的數據在R中

  1. 隨機打亂我的時間序列
  2. 子集的前5行該數據的
  3. 計算此數據子集的Spearman等級相關性。
  4. 重複此操作100次
  5. 將每個新計算的關聯追加到同一個csv文件中。

我覺得一個「for」循環會做最好的(但我接受其他的建議非常開放!),所以我現在有以下幾點:

shuffled= NULL 
for (n in 1:100){ 

    shuffled[n]=mydata[sample(nrow(mydata)),] 
    subset[n]<- shuffled[c(1:5),] 
    correlations[n] <- cor(subset$col1,subset$col2,, method="spearman") 
    write.table(correlations, file="", quote=FALSE, append=TRUE, row.names=FALSE, col.names=FALSE) 

} 

目前,這是給我下面的錯誤信息:

Error in shuffled[c(1:5), ] : incorrect number of dimensions 

,也是一個警告消息:

In shuffled[n] = mydata[sample(nrow(mydata)), ] : number of items to replace is not a multiple of replacement length 

我一直在尋找一個解決方案几個小時。我也沒有使用循環的經驗。非常感謝您的幫助。

回答

0

雖然有更好的方法來執行此操作,但您遇到的關鍵錯誤是shuffled應該是list而不是vector

然後,索引列表,使用雙括號,[[(不[單)

初始化爲

shuffled <- list() 
correlations <- list() 
... 
shuffled[[n]] <- ... 

另外,如果你沒有需要保留的洗後/相關值,你只是輸出到文件,我會做以下幾點:

correlations <- lapply(seq(100), function(n) { 
         ## Instead... just sample five directly 
         ## subset <- mydata[sample(nrow(mydata)), ] [1:5, ] 
         subset <- mydata[sample(nrow(mydata), 5), ] 
         cor(subset$col1,subset$col2,, method="spearman") 
        }) 


## Flatten the list into a single data.frame, then output into 
correlations <- do.call(rbind, correlations) 

write.table(correlations, ... etc) 
+0

非常感謝。我更喜歡你的建議方法,因爲我不需要保持「洗牌」等等。但是,運行它時我獲得了以下錯誤消息 - 我必須錯過某些明顯的東西。 [.data.frame(mydata,sample(nrow(mydata)))中的錯誤:未定義列被選中 – Jess

+0

在'['中的行索引後面缺少逗號(',')。我已經更新了我的答案 –