You are currently viewing R – Import Text File as a String

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.

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)

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")

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")

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)

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.

Related Articles

References

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium