Import Text File as Single Character String in R (Example)
In this R tutorial you’ll learn how to read a TXT file as a single character string.
The tutorial will consist of this information:
Let’s dive into it:
Creating TXT Example File
Before we can jump into the example code, we need to create an example TXT file on our computer.
Let’s assume that we have a folder on our computer that is called my_directory. In this directory, we have stored a TXT file that looks as follows:
Looks good – let’s load this file into R!
Example: Import TXT File as Character String Using read_file Function of readr Package
This section illustrates how to read a text file as a single character string into R.
First, we have to specify the path to our directory where the file is stored as well as the name of our file:
my_path <- "C:/Users/Joach/Desktop/my_directory/" # Specify directory my_file_name <- "my_text_file.txt" # Specify file name
Next, we have to install and load the readr package:
install.packages("readr") # Install readr package library("readr") # Load readr package
Now, we can use the read_file function of the readr package to import our TXT file as character string:
imported_text <- read_file(paste0(my_path, my_file_name)) # Apply read_file function imported_text # Print character string to console # [1] "hello, this is my text.\r\nit contains several lines and weird spaces at some\r\nP\r\nO\r\nI\r\nN\r\nT\r\nS\r\n!\r\n"
That worked well!
Video, Further Resources & Summary
If you need further information on the R programming code of this article, you might watch the following video of my YouTube channel. I’m explaining the R codes of this post in the video:
The YouTube video will be added soon.
In addition, you may want to have a look at the related posts on my website:
- Count Number of Words in Character String
- Convert Character String to Date Object
- Print Character String to Newline of RStudio Console
- Test if Character is in String
- R Programming Examples
You learned in this tutorial how to import TXT files as a character in the R programming language. Please let me know in the comments below, if you have further questions. Furthermore, please subscribe to my email newsletter in order to receive regular updates on the newest articles.