Add New Line to Text File in R (Example)
In this post, I’ll show how to append a new line to an already existing TXT file in the R programming language.
Table of contents:
Let’s get started…
Constructing Example Data
The TXT file shown in the screenshot below will be used as basement for this R tutorial:
Furthermore, we have to create a data object containing the new line that we want to add to this file formatted as a character string:
my_line <- "This is a very new line that I want to add!" # New line
Example: Append New Line to Text File Using write() Function
This example explains how to add a new line of text to a TXT file in R.
For this, we can apply the write function in combination with the append argument as you can see below:
write(my_line, # Write new line to file file = "my file.txt", append = TRUE)
Have a look at the previously shown screenshot. It shows our updated TXT file containing an additional line of text.
Video & Further Resources
Have a look at the following video of my YouTube channel. I’m explaining the R code of this tutorial in the video:
Furthermore, you might read the other tutorials of my website. I have released numerous articles about related topics such as graphics in R, text elements, importing data, and character strings.
- Import Text File as Single Character String
- Add Text to Plot Using text() Function in Base R
- scan Function (5 Example Codes) in R
- R Programming Overview
You have learned in this article how to add a new line of text to a TXT file in R programming. Let me know in the comments section below, if you have any further questions or comments.