チャンクを data.frame として読み込む
前の例では、mstrsplit() を使って各チャンクを行列として処理関数に渡していました。各列で要素の型が同じという前提の、長方形データを読む場合はこれで問題ありません。そうでない場合は、データを data.frame として読み込みたくなることがあります。これは、チャンクを一度行列として読み込んでから data.frame に変換する方法もありますし、dstrsplit() 関数を使って直接読み込むこともできます。
この演習はコースの一部です
Rで学ぶスケーラブルなデータ処理
演習の手順
- 関数
make_msa_table()の中で、各チャンクをデータフレームとして読み込みます。 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
___