导入CSV时选择指定的行 [英] Select specified rows when importing CSV

查看:83
本文介绍了导入CSV时选择指定的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的CSV文件,如果要导入,则只想选择某些行.首先,我创建将要导入的行的索引,然后希望将这些行的名称传递给sqldf并返回指定行的完整记录.

I have a large CSV file and I only want to import select certain rows if it. First I create the indices of the rows that will be imported then I wish to pass the names of these rows to sqldf and return the full records for specified rows.

#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文件导入选择的行?

How to import a selection of rows from a CSV file by specifying the row numbers?

推荐答案

尝试以下示例:

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)

这篇关于导入CSV时选择指定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆