sagar sethi
sagar sethi

Reputation: 3

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. 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. I am a beginner in R-Language, so I find the syntax a bit confusing.

    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.

Upvotes: 0

Views: 1353

Answers (1)

agstudy
agstudy

Reputation: 121568

  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.

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)

Upvotes: 2

Related Questions