开始使用免费开始使用

将分块读入为 data.frame

在上一个示例中,我们使用 mstrsplit() 将每个分块读入处理函数为矩阵。对于读取"每列元素类型相同"的规则矩形数据,这样做没有问题。但当列类型不一致时,您可能希望将数据读入为 data.frame。这可以通过两种方式实现:先将分块读成矩阵再转换为 data.frame,或者直接使用 dstrsplit() 函数。

本练习是课程的一部分

R 的可扩展数据处理

查看课程

练习说明

  • 在函数 make_msa_table() 中,将每个分块读入为 data frame。
  • 调用 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
___
编辑并运行代码