我有一个很大的 CSV 文件,我只想导入选择某些行。首先,我创建将要导入的行的索引,然后我希望将这些行的名称传递给 sqldf 并返回指定行的完整记录。
#create the random rows ids that will be sampled
library(dplyr)
#range for the values
index<-c(1:20)
index<-as.data.frame(as.matrix(index))
#number of values to be returned
number<-5
ids<-sample_n(index,number)
#sample the data
library(sqldf)
#filepath
f<-file("/Users/.../filename.csv")
#select data
df<-sqldf("select * from f")
如何通过指定行号从 CSV 文件中导入选择的行?
最佳答案
试试这个例子:
library(sqldf)
#dummy csv
write.csv(data.frame(myid=1:10,var=runif(10)),"temp.csv")
#define ids
ids <- c(1,3,4)
ids <- paste(ids,collapse = ",")
f <- file("temp.csv")
#query with subset
fn$sqldf("select *
from f
where myid in ($ids)",
file.format = list(header = TRUE, sep = ","))
#output
# X myid var
# 1 "1" 1 0.2310945
# 2 "3" 3 0.8825055
# 3 "4" 4 0.6655517
close(f)
关于r - 导入 CSV 时选择特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30527587/