始める無料で始める

年度別の借り手地域

この演習では、年度と msa(都市 vs 農村)変数でデータを集計します。

この演習はコースの一部です

Rで学ぶスケーラブルなデータ処理

コースを見る

演習の手順

必要なパッケージはすべてワークスペースに読み込まれています。

  • チャンクを行列として読み込み、借り手の地域(msa)と年度で集計する関数 make_table() を作成してください。
  • こちらで用意したファイル接続からデータを取り込むために、chunk.apply() を使ってください。
  • 残りのコードを実行して、地域ごとの住宅ローン受給の推移をプロットしましょう。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Open a connection to the file and skip the header
fc <- file("mortgage-sample.csv", "rb")
readLines(fc, n = 1)

# Create a function to read chunks
make_table <- function(chunk) {
    # Create a matrix
    m <- ___(___, sep = ",", type = "integer")
    colnames(m) <- mort_names
    # Create the output table
    ___(___, c(___, ___))
}

# Import data using chunk.apply
msa_year_table <- ___

# Close connection
close(fc)

# Convert to a data frame
df_msa <- as.data.frame(msa_year_table)

# Rename columns
df_msa$MSA <- c("rural", "city")

# Gather on all columns except Year
df_msa_long <- pivot_longer(df_msa, -MSA, names_to = "Year", values_to = "Count")

# Plot 
ggplot(df_msa_long, aes(x = Year, y = Count, group = MSA, color = MSA)) + 
    geom_line()
コードを編集して実行