Smith Black
Smith Black

Reputation: 535

How to read a txt file line by line in R/Rstudio?

Suppose I have a messy text file like the following for example

Today is a good
day, but I feel very tired. It seems like it is
going to rain pretty soon.

I want to read the txt file into R as a character vector exactly the way it appears as in the original text file. In other words, I want to have the first element of the character vector being the first line, second element of the character vector being the second line, etc, as below

char_vector[1] = "Today is a good"
char_vector[2] = "day, but I feel very tired. It seems like it is"
char_vector[3] = "going to rain pretty soon."

I have tried read.table and read.csv, but it's always the case that some lines join together as one line. Is there a way to fix this?

Upvotes: 4

Views: 7825

Answers (3)

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

scan can do this.

scan( file="myfile.txt", what=character() ) 

Upvotes: 1

IRTFM
IRTFM

Reputation: 263301

char_vector <- readLines(filename)

 txt <- "Today is a good
 day, but I feel very tired. It seems like it is
 going to rain pretty soon."

 readLines(textConnection(txt) )
#   ---- teh screen output of three distinct character elements
[1] "Today is a good"                                
[2] "day, but I feel very tired. It seems like it is"
[3] "going to rain pretty soon."                    

char_vector <- readLines(textConnection(txt))

char_vector[1]
#[1] "Today is a good"

Upvotes: 6

user1436187
user1436187

Reputation: 3376

You can use readLines function.

Upvotes: 1

Related Questions