问题
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