Import text file as single character string

How about:

string <- readChar("foo.txt",nchars=1e6)

Here's a variant of the solution from @JoshuaUlrich that uses the correct size instead of a hard-coded size:

fileName <- 'foo.txt'
readChar(fileName, file.info(fileName)$size)

Note that readChar allocates space for the number of bytes you specify, so readChar(fileName, .Machine$integer.max) does not work well...


I would use the following. It should work just fine, and doesn't seem ugly, at least to me:

singleString <- paste(readLines("foo.txt"), collapse=" ")

In case anyone is still looking at this question 3 years later, Hadley Wickham's readr package has a handy read_file() function that will do this for you.

# you only need to do this one time on your system
install.packages("readr")
library(readr)
mystring <- read_file("path/to/myfile.txt")

Tags:

R