借款人地区按年份
在本练习中,您将按年份和 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()