Wednesday, May 22, 2013

Learning R

Reading and Writing File line by line in R :

Here is small program for reading and writing file line by line instead of whole file in R.




con <- file('D:/R_Work/train-test.csv', 'r')
conOp <- file('R_Work/train_modified1.csv', 'w')
while (length(input <- readLines(con, n=1000)) > 0)
{
  for (i in seq_along(input))
  {
    words <- strsplit(input[i],",")[[1]];
   op=""
    for(var in 1 : length(words))
    {
     
      if( var == 2)
      {
        words[var] ="R_ID"
      }
      if(var == 1)
      {
        op <- words[var];
      }
      else
      {
        op<-c(op,words[var]);
      }
     
    }
   
    print("Printing#######################################")
    output <- paste(op,collapse=",");
    print(output);
    writeLines(output, conOp)  
  }
 
}
close(con)
close(conOp)

No comments:

Post a Comment