開始使用免費開始

除錯相關性的問題

你在美國衛生部工作。你的團隊正在調查多胞胎懷孕(雙胞胎、三胞胎等)是否與孕期體重增加較多有關。你已經計算過相關係數,但結果與另一位分析師的估計值差異很大。她指出,你的資料沒有記錄超過 99 磅的體重增加值。你決定重新進行計算,這次你想把孕期體重增加的最大值記錄到日誌裡。

在你的工作空間中,有一個資料框清單 ls_dfls_df 的每個元素都包含各州的出生資料。你已經寫好一個 foreach 迴圈來平行執行計算。

foreachdoParallel 已為你載入。

本練習屬於課程

R 平行程式設計

檢視課程

練習說明

  • 建立一個包含 4 個核心的叢集。
  • 指定一個名為 state_log.txt 的檔案,將叢集產生的訊息寫入該日誌。
  • 在迴圈本體中,記錄資料框 df 中欄位 weight_gain_pounds 的最大值。
  • 讀取 state_log.txt 檢查列印的訊息。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create a cluster of four cores
cl <- ___(___,
# Specify a file to log print statements                    
          ___ = "___")
registerDoParallel(cl)
res <- foreach(df = ls_df) %dopar% {
   print(paste(unique(df$state), ":",
# Calculate maximum of weight_gain_pounds in df
               ___(___)))
                 
  cor(df$plurality, df$weight_gain_pounds)
}
stopCluster(cl)
# Read log file to check print messages
read.delim("___", sep = ";")
編輯並執行程式碼