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

R Text File String

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

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