How to import a text file in R as a character vector

I would like to know if a simple command exists in Rthat already exists and will allow importing a char text file (.txt) into a char vector.

The file may be English text with a string like "Hello my name is Fagui Curtain" and output in the vector will be R char A such that A[1]<-"H", A[2]<-"e", A[3]<-"l"etc.

I tried the scan function, but would return words A[1]<-"Hello", A[2]<-"my"....

I searched my question but did not find anything useful.

thank

+4
source share
2 answers

Try strsplitafter removing the space withgsub

A <- strsplit(gsub('\\s+', '', lines),'')[[1]]
A
#[1] "H" "e" "l" "l" "o" "m" "y" "n" "a" "m" "e" "i" "s" "F" "a" "g" "u" "i" "C"
#[20] "u" "r" "t" "a" "i" "n"

or

library(stringi)
stri_extract_all_regex(lines, '\\w')[[1]]
#[1] "H" "e" "l" "l" "o" "m" "y" "n" "a" "m" "e" "i" "s" "F" "a" "g" "u" "i" "C"
#[20] "u" "r" "t" "a" "i" "n"

Or if you are using linux scanand pass usingawk

scan(pipe("awk 'BEGIN{FS=\"\";OFS=\" \"}{$1=$1}1' file.txt"), 
                  what='', quiet=TRUE)
#[1] "H" "e" "l" "l" "o" "m" "y" "n" "a" "m" "e" "i" "s" "F" "a" "g" "u" "i" "C"
#[20] "u" "r" "t" "a" "i" "n"

data

lines <- readLines('file.txt')
+8

stringr ( , ).

sample_text

Hello my name is Fagui Curtain

require(stringr)
testVector <- str_split(readLines("sample_text.txt"), pattern = " ")
+1

Source: https://habr.com/ru/post/1584632/


All Articles