0 votes
1 view
in R Programming by (6.5k points)

How do you import a plain text file as a single character string in R? I think that this will probably have a very simple answer but when I tried this today I found that I couldn't find a function to do this.

For example, suppose I have a file foo.txt with something I want to examine.

I tried it with:

scan("foo.txt", what="character", sep=NULL)

but this still returned a vector. I got it working somewhat with:

paste(scan("foo.txt", what="character", sep=" "),collapse=" ")

but that is quite an ugly solution which is probably unstable too.

1 Answer

0 votes
by (25.3k points)

To import a text file as a single character, use the read_file() function from the readr package in R as follows:

library(readr)

myString <- read_file("C:/Users/intellipaat/Desktop/Questions/FILE1.txt")


mystring

[1] "HELLO WORLD"

str(mystring)

chr "HELLO WORLD"

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...