將區塊讀入為 data.frame
在前一個範例中,我們使用 mstrsplit() 將每個區塊讀成矩陣,然後傳入處理函式。當讀取的是每欄元素型別都相同的矩形資料時,這樣做沒問題。但若不是這種情況,你可能會想把資料讀成 data.frame。你可以先把區塊讀成矩陣再轉成 data.frame,或是直接使用 dstrsplit() 函式。
本練習屬於課程
R 的可擴展資料處理
練習說明
- 在
make_msa_table()函式中,將每個區塊讀成 data frame。 - 呼叫
chunk.apply()以區塊方式讀入資料。 - 將所有列相加,取得每欄的總計。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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
___