我有一个 .csv 文件:example.csv,包含 8000 列 x 40000 行。 csv 文件的每一列都有一个字符串标题。所有字段都包含 0 到 10 之间的整数值。当我尝试使用 read.csv 加载此文件时,结果发现速度非常慢。当我添加参数nrow=100时也很慢。我想知道是否有办法加速 read.csv,或者使用其他函数而不是 read.csv 将文件作为矩阵或 data.frame 加载到内存中?
提前致谢。
最佳答案
如果您的 CSV 仅包含整数,则应使用 scan
而不是 read.csv
,因为 ?read.csv
表示:
‘read.table’ is not the right tool for reading large matrices,
especially those with many columns: it is designed to read _data
frames_ which may have columns of very different classes. Use
‘scan’ instead for matrices.
由于您的文件有 header ,因此您将需要 skip=1
,如果您设置 what=integer()
,速度可能会更快。如果您必须使用 read.csv
并且担心速度/内存消耗,那么设置 colClasses
参数会有很大帮助。
关于read.csv 在读取具有大量列的 csv 文件时非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7327851/