chunk.apply

R 的可擴展資料處理

Simon Urbanek

Member of R-Core, Lead Inventive Scientist, AT&T Labs Research

chunk.apply()

  • 抽象化迴圈流程
  • 可啟用平行執行
  • iotoolshmr 的基礎,可在 Apache Hadoop 基礎設施上處理資料
R 的可擴展資料處理

mstrsplit() 以矩陣讀入區塊

# Use chunk.apply to get chunks of rows from foo.csv
chunk_col_sums <- chunk.apply("foo.csv",

# A function to process each of the chunk function(chunk) { # Turn the chunk into a matrix m <- mstrsplit(chunk, type = "numeric", sep = ",") # Return the column sums colSums(m) }, # Maximum chunk size in bytes CH.MAX.SIZE = 1e5)
# Get the total sum colSums(chunk_col_sums)
R 的可擴展資料處理

dstrsplit() 以資料框讀入區塊

# Use chunk.apply to get chunks of rows from foo.csv
chunk_col_sums <- chunk.apply("foo.csv",

 # A function to process each of the chunk
 function(chunk) {
   # Turn the chunk into a data frame
   d <- dstrsplit(chunk, col_types = rep("numeric", 3), sep = ",")
   # Return the column sums
   colSums(d)
 }, 
 # Maximum chunk size in bytes
 CH.MAX.SIZE = 1e5)

# Get the total sum
colSums(chunk_col_sums)
R 的可擴展資料處理

平行化 chunk.apply()

# Use chunk.apply to get chunks of rows from foo.csv
chunk_col_sums <- chunk.apply("foo.csv",

 # A function to process each of the chunk
 function(chunk) {

   # Turn the chunk into a data frame
   d <- dstrsplit(chunk, col_types = rep("numeric", 3), sep = ",")
   colSums(d)
 }, 
 # 2 processors read and process data
 CH.PARALLEL = 2)

# Get the total sum
colSums(chunk_col_sums)
R 的可擴展資料處理

關於平行化的注意事項

  • 處理器數量增加,不一定會讓程式更快
  • 在單機上加更多處理器,效益通常會遞減
R 的可擴展資料處理

一起來練習吧!

R 的可擴展資料處理

Preparing Video For Download...