เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ภูมิภาคของผู้กู้แยกตามปี

ในแบบฝึกหัดนี้ คุณจะสร้างตารางสรุปข้อมูลโดยแบ่งตามปีและตัวแปร msa (เมืองหรือชนบท)

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การประมวลผลข้อมูลขนาดใหญ่ใน R

ดูคอร์ส

คำแนะนำการฝึกหัด

แพ็กเกจที่จำเป็นทั้งหมดถูกโหลดไว้ใน workspace แล้ว

  • สร้างฟังก์ชัน make_table() ที่อ่าน chunk เป็น matrix แล้วสร้างตารางสรุปตามภูมิภาคของผู้กู้ (msa) และปี
  • ใช้ chunk.apply() เพื่อนำเข้าข้อมูลจาก file connection ที่เตรียมไว้ให้
  • รันโค้ดส่วนที่เหลือเพื่อพล็อตกราฟแสดงการเปลี่ยนแปลงของจำนวนสินเชื่อที่อยู่อาศัยแยกตามภูมิภาค

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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()
แก้ไขและรันโค้ด