13

How do I go about in replacing the nth line of a text file in R?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Simanner
  • 183
  • 1
  • 5
  • 3
    Have you looked at help(readLines)? – Spacedman Aug 01 '12 at 09:32
  • 3
    Welcome to Stack Overflow! To the person who silently downvoted: This is the [summer of love](http://blog.stackoverflow.com/2012/07/kicking-off-the-summer-of-love/), so I suggest you do one of a few things 1) Explain why the downvote, 2) Explain to the OP how to improve the question 3) Edit the question so it is a good question. – Andrie Aug 01 '12 at 09:53
  • Thanks for the explanation. I had looked at readLines but I did not know about writeLines. – Simanner Aug 01 '12 at 12:07
  • 1
    @Simanner: I recommend you always read the "See Also" section of the help pages. Had you read the "See Also" section of `?readLines`, you would have seen `writeLines`. – Joshua Ulrich Aug 01 '12 at 12:25

2 Answers2

28

To replace the third line of this:

$ cat junk.txt
sic transit
gloria mundi
temeo danoas
et dona ferentes

Do this:

> latin = readLines("junk.txt",-1)
> latin[3]="per ardua ad astra"
> writeLines(latin,"junkout.txt")

and get:

$ cat junkout.txt 
sic transit
gloria mundi
per ardua ad astra
et dona ferentes

You can writeLines(latin,"junk.txt") and overwrite the input file if you want.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
2

I don't know if there is an option to change a specific line in the streaming file (seek in file), although you have the option to read the file , change a column and write the the frame to a file, read, write functions supply you what you need.

You may also use read.table() to read the file into a table format, change specific row and then write.table()

you have options like read.csv() and write.csv() and many other options like readLines().

EDIT

Here is a wiki link for file handling in R

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Michael
  • 2,827
  • 4
  • 30
  • 47
  • 4
    Please be careful when posting answers. R is case-sensitive, so `readlines` is not the same as `readLines`, and there is actually a function `readline`. – A5C1D2H2I1M1N2O1R2T1 Aug 01 '12 at 09:47