依年份統計借款人地區
在這個練習中,你將依年份與 msa(都市 vs. 鄉村)變數來製作資料列聯表。
本練習屬於課程
R 的可擴展資料處理
練習說明
所有需要的套件都已載入到你的工作環境中。
- 建立一個函式
make_table(),將每個區塊讀成矩陣,接著依借款人地區(msa)與年份進行彙整成表格。 - 使用
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()