How to read or import data from a text file as a character string in R? R provides several ways to do so but one thing you need to remember is that loading large files of data into a string will result in memory issues hence, keep this in mind.
<a id="h-1-quick-examples"></a>
1. Quick Examples
Following are quick examples of different ways to read or import a text file into a string variable.
# Quick Examples
# Read text file into string
file_str <- paste(readLines("/users/admin/file.txt"), collapse="\n")
# Using readr package
library(readr)
file_str <- read_file("/users/admin/file.txt")
# Read Text File as String
text_file <- '/users/admin/file.txt'
file_str = readChar(text_file, file.info(text_file)$size)
<a id="h-2-read-text-file-into-string"></a>
2. Read Text File into String
To read or load the content of the text file into a string variable use the below approach. Use collapse='\n' to collapse all lines into a single line. This approach works well for compressed files as well.
# Read text file into string
file_str <- paste(readLines("/users/admin/file.txt"), collapse="\n")
<a id="h-3-using-readr-package"></a>
3. Using readr Package
If you are working with larger files, you should use the read_file() function readr package. readr is a third-party library hence, in order to use readr library, you need to first install it by using install.packages('readr'). Once installation completes, load the readr library in order to use this read_file() method. To load a library in R use library("readr").
# Using readr package
library(readr)
file_str <- read_file("/users/admin/file.txt")
<a id="h-4-using-readchar-function"></a>
4. Using readChar() Function
This allocates the memory with the size of the file and then loads it into a variable. This is the least preferred option.
# Read Text File as String
text_file <- '/users/admin/file.txt'
file_str = readChar(text_file, file.info(text_file)$size)
<a id="h-5-conclusion"></a>
5. Conclusion
In this article, you have learned how to read or load the content of a text file into a string variable in R. For faster performance, use read_file() from readr package.
<a id="h-related-articles"></a>
Related Articles
- R Read Text File to DataFrame
- Read CSV From URL in R
- Read Multiple CSV Files in R
- How to Import Excel File in R?
- How to Export Excel File in R?
- How to Import CSV File in R?
- How to Export CSV File in R?
- How to write Text File to Data Frame?
- Efficient data import guide in R.
- How to read JSON file in R?
- Explain Collapse method in R.
- Explain tryCatch() function in R.
- 50 R Programming interview questions and answers.
- Export data from R complete guide.
<a id="h-references"></a>
