Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

text

r

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?

like image 759
Smith Black Avatar asked Oct 14 '25 14:10

Smith Black


1 Answers

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"
like image 100
IRTFM Avatar answered Oct 17 '25 05:10

IRTFM