ComenzarEmpieza gratis

Leer bloques como data.frame

En el ejemplo anterior, leímos cada bloque en la función de procesamiento como una matriz usando mstrsplit(). Esto está bien cuando leemos datos rectangulares donde el tipo de elemento en cada columna es el mismo. Cuando no lo es, puede interesarte leer los datos como un data.frame. Esto se puede hacer leyendo un bloque como matriz y luego convirtiéndolo a data.frame, o bien usando la función dstrsplit().

Este ejercicio forma parte del curso

Procesamiento de datos escalable en R

Ver curso

Instrucciones del ejercicio

  • En la función make_msa_table(), lee cada bloque como un data.frame.
  • Llama a chunk.apply() para leer los datos por bloques.
  • Obtén los recuentos totales de cada columna sumando todas las filas.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# 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
___
Editar y ejecutar código