Read csv file with selected rows using data.table's fread

喜你入骨 提交于 2021-01-29 17:36:01

问题


I was going through some earlier post-

Quickest way to read a subset of rows of a CSV

One way to select subset of data is

write.csv(iris,"iris.csv")

fread("shuf -n 5 iris.csv")

However I was wondering if I can pass some SQL query instead of top 5 rows e.g. only import those rows that have V6 = versicolor

Is there any way to do this using fread function?


回答1:


This worked for me in windows (unix alternative is grep)

write.csv(iris,"iris.csv")

fread(cmd = paste('findstr', 'versicolor', 'iris.csv'))

    V1  V2  V3  V4  V5         V6
 1:  51 7.0 3.2 4.7 1.4 versicolor
 2:  52 6.4 3.2 4.5 1.5 versicolor
 3:  53 6.9 3.1 4.9 1.5 versicolor
 4:  54 5.5 2.3 4.0 1.3 versicolor
 5:  55 6.5 2.8 4.6 1.5 versicolor
 6:  56 5.7 2.8 4.5 1.3 versicolor
 7:  57 6.3 3.3 4.7 1.6 versicolor
 8:  58 4.9 2.4 3.3 1.0 versicolor
 9:  59 6.6 2.9 4.6 1.3 versicolor
10:  60 5.2 2.7 3.9 1.4 versicolor
11:  61 5.0 2.0 3.5 1.0 versicolor

It outputs only those rows that contain "versicolor" in any field.



来源:https://stackoverflow.com/questions/56851587/read-csv-file-with-selected-rows-using-data-tables-fread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!