IniziaInizia gratis

Lettura di chunk come data.frame

Nell'esempio precedente, abbiamo letto ogni chunk nella funzione di elaborazione come matrice usando mstrsplit(). Questo va bene quando leggiamo dati rettangolari in cui il tipo di elemento in ogni colonna è lo stesso. Quando non è così, potremmo preferire leggere i dati come data.frame. Questo si può fare leggendo un chunk come matrice e poi convertendolo in un data.frame, oppure puoi usare la funzione dstrsplit().

Questo esercizio fa parte del corso

Elaborazione scalabile dei dati in R

Visualizza il corso

Istruzioni dell'esercizio

  • Nella funzione make_msa_table(), leggi ogni chunk come data frame.
  • Chiama chunk.apply() per leggere i dati a chunk.
  • Ottieni i conteggi totali per ciascuna colonna sommando tutte le righe.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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
___
Modifica ed esegui il codice