연도별 차입자 지역
이 연습 문제에서는 연도와 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()