简体   繁体   English

以R语言读取CSV文件的特定行

[英]Read SPecific lines of a CSV file in R-language

I am trying to write a code which manipulates data from a particular .csv and writes the data to another one. 我正在尝试编写一个代码来处理来自特定.csv的数据并将数据写入另一个。 I want to read each line one by one and perform the operation. 我想逐个读取每一行并执行操作。 Also I am trying to read a particular line from the .csv but what I am getting is that line and the lines before it. 此外,我试图从.csv读取一个特定的行,但我得到的是该行和它之前的行。 I am a beginner in R-Language, so I find the syntax a bit confusing. 我是R语言的初学者,所以我发现语法有点令人困惑。

    testconn<=file("<path>")
    num<-(length(readLines(testconn)))
    for(i in 1:num){
    num1=i-1
    los<=read.table(file="<path>",sep=",",head=FALSE,skip=num1,nrows=1)[,c(col1,col2)]
    write.table(los,"<path>",row.names=FALSE,quote=FALSE,sep=",",col.names=FALSE,append=TRUE)
    }

This is the code I am currently using, thought it is giving the desiored output but it is extremely slow, my .csv data file has 43200 lines. 这是我目前正在使用的代码,认为它提供的是desiored输出,但它非常慢,我的.csv数据文件有43200行。

  1. Your code doesn't work. 您的代码不起作用。 You confuse the comparison operator <= and the assignment one <- 你混淆比较运算符<=和赋值一< -
  2. Your code is is extremly innefficient. 你的代码极其无效。 You call both read.table and write.table 43200 times to read/write a single file . 你同时调用read.tablewrite.table 43200次来读/写一个文件

You can simply do this: 你可以这样做:

    los<- read.table(file="<path>",sep=",")[,c(col1,col2)]
    res <- apply(los,1,function(x){## you treat your line here}
    write.table(res,"<path_write>",row.names=FALSE,
                       quote=FALSE,sep=",",col.names=FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM