使用fread函数(data.table),用户可以使用'select'参数定义要读入的数据帧的特定列(例如fread(input,select = c(1,5,10))。我也希望如此能力,但对于行(例如fread(input,selectrows = c(1,4,47))。读取文件后,我可以执行此操作,但这需要很长时间,我希望优化通过仅读取我需要的行来进行处理。
我知道许多基于“文件内”条件以编程方式选择行的选项:
Read csv file with selected rows using data.table's fread
Quickest way to read a subset of rows of a CSV
...但是我希望能够使用基于要读取的给定文件之外的标准定义的向量(如question中一样,但特别是使用fread)。
一种方法(虽然有点蛮力)是使用sed
剪切线。
回想一下fread
和file=
一样,也取[C0
cmd=
(由于[C0]不知道/不在意标题行,所以有两行。]
尝试一下:
library(data.table)
fwrite(iris, "iris.csv")
fread(cmd = "head -n 3 iris.csv")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1: 5.1 3.5 1.4 0.2 setosa
# 2: 4.9 3.0 1.4 0.2 setosa