시작하기무료로 시작하기

청크를 data.frame으로 읽기

이전 예제에서는 mstrsplit()을 사용해 각 청크를 행렬로 처리 함수에 전달했어요. 이런 방식은 각 열의 요소 유형이 동일한 직사각형 형태의 데이터를 읽을 때는 괜찮습니다. 하지만 그렇지 않은 경우에는 데이터를 data.frame으로 읽어들이는 것이 좋습니다. 이는 청크를 먼저 행렬로 읽은 뒤 data.frame으로 변환하거나, dstrsplit() 함수를 사용해 직접 data.frame으로 읽어 처리할 수 있습니다.

이 연습은 강의의 일부입니다

R에서 확장 가능한 데이터 처리

강의 보기

연습 안내

  • make_msa_table() 함수에서 각 청크를 데이터 프레임으로 읽어들이세요.
  • chunk.apply()를 호출해 데이터를 청크 단위로 읽으세요.
  • 모든 행을 더해 각 열의 총합을 구하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Define the function to apply to each chunk
make_msa_table <- function(chunk) {
    # Read each chunk as a data frame
    x <- ___(chunk, col_types = rep("integer", length(col_names)), sep = ",")
    # Set the column names of the data frame that's been read
    colnames(x) <- col_names
    # Create new column, msa_pretty, with a string description of where the borrower lives
    x$msa_pretty <- msa_map[x$msa + 1]
    # Create a table from the msa_pretty column
    table(x$msa_pretty)
}

# Create a file connection to mortgage-sample.csv
fc <- file("mortgage-sample.csv", "rb")

# Read the first line to get rid of the header
readLines(fc, n = 1)

# Read the data in chunks
counts <- ___(fc, ___, CH.MAX.SIZE = 1e5)

# Close the file connection
close(fc)

# Aggregate the counts as before
___
코드 편집 및 실행