การอ่านข้อมูลแบบ chunk เป็น data.frame
ในตัวอย่างก่อนหน้า เราอ่านข้อมูลแต่ละ chunk เข้าสู่ฟังก์ชันประมวลผลในรูปแบบ matrix โดยใช้ mstrsplit() วิธีนี้เหมาะสำหรับข้อมูลที่มีโครงสร้างสี่เหลี่ยม ซึ่งแต่ละคอลัมน์มีชนิดข้อมูลเดียวกัน แต่เมื่อข้อมูลแต่ละคอลัมน์มีชนิดที่แตกต่างกัน เราอาจต้องการอ่านข้อมูลเป็น data.frame แทน ซึ่งทำได้โดยอ่าน chunk เป็น matrix แล้วแปลงเป็น data.frame หรือจะใช้ฟังก์ชัน dstrsplit() โดยตรงก็ได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การประมวลผลข้อมูลขนาดใหญ่ใน R
คำแนะนำการฝึกหัด
- ในฟังก์ชัน
make_msa_table()ให้อ่านข้อมูลแต่ละ chunk เป็น data frame - เรียกใช้
chunk.apply()เพื่ออ่านข้อมูลทีละ chunk - หาผลรวมทั้งหมดของแต่ละคอลัมน์โดยรวมค่าจากทุกแถว
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define the function to apply to each chunk
make_msa_table <- function(chunk) {
# Read each chunk as a data frame
x <- ___(chunk, col_types = rep("integer", length(col_names)), sep = ",")
# Set the column names of the data frame that's been read
colnames(x) <- col_names
# Create new column, msa_pretty, with a string description of where the borrower lives
x$msa_pretty <- msa_map[x$msa + 1]
# Create a table from the msa_pretty column
table(x$msa_pretty)
}
# Create a file connection to mortgage-sample.csv
fc <- file("mortgage-sample.csv", "rb")
# Read the first line to get rid of the header
readLines(fc, n = 1)
# Read the data in chunks
counts <- ___(fc, ___, CH.MAX.SIZE = 1e5)
# Close the file connection
close(fc)
# Aggregate the counts as before
___