I am trying to write code in r that:
1.)Reads every other line in a text file
2.)writes those lines to a text file
My code does these things, but the problem is that r is writing the lines to the text file in continuous format, instead of writing line by line like the original text file.
Here is my code:
test <- readLines("file_name.txt")
test <- test[seq(1, length(test), 2)] # reads every 2nd line
cat(test, file="E:/output_file_name.txt", sep = " ",append=TRUE)
In the original file "file_name.txt" the lines are like this:
"2013-05-30",15,30,55,95
"2013-05-31",27,97,77,88
"2013-06-01",50,99,81,82
And I am reading every other line such that r outputs every other line to a text file. But the problem is that when I output to the text file titled "output_file_name.txt" what the text file looks like is:
"2013-05-30",15,30,55,95 "2013-06-01",50,99,81,82
But what I need the text file to look like is :
"2013-05-30",15,30,55,95
"2013-06-01",50,99,81,82
The original text file is so large that it would be impossible to edit by hand.
Please help,
Thank you
I prefer the write
functions for writing to file. I think this does what you want.
> txt <- '"2013-05-30",15,30,55,95
"2013-05-31",27,97,77,88
"2013-06-01",50,99,81,82'
> test <- readLines(textConnection(txt))
> test <- test[seq(1, length(test), 2)]
> writeLines(test, sep = "\n") ## with file = "filename" to write to file
"2013-05-30",15,30,55,95
"2013-06-01",50,99,81,82
All you needed was a sep = "\n"
in there. Or you could insert "\n"
into the end of each string, but that's overkill.