chunk.apply

Xử lý dữ liệu có khả năng mở rộng trong R

Simon Urbanek

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

chunk.apply()

  • Trừu tượng hóa quá trình lặp
  • Cho phép thực thi song song
  • iotools là nền tảng của hmr, cho phép bạn xử lý dữ liệu trên hạ tầng Apache Hadoop
Xử lý dữ liệu có khả năng mở rộng trong R

mstrsplit() đọc từng khối dưới dạng ma trận

# 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)
Xử lý dữ liệu có khả năng mở rộng trong R

dstrsplit() đọc từng khối dưới dạng data frame

# 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)
Xử lý dữ liệu có khả năng mở rộng trong R

Song song hóa 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)
Xử lý dữ liệu có khả năng mở rộng trong R

Lưu ý về song song hóa

  • Tăng số bộ xử lý không phải lúc nào cũng giúp mã chạy nhanh hơn
  • Thường có hiện tượng lợi ích giảm dần khi thêm bộ xử lý trên một máy đơn lẻ
Xử lý dữ liệu có khả năng mở rộng trong R

Cùng luyện tập nào!

Xử lý dữ liệu có khả năng mở rộng trong R

Preparing Video For Download...