string - how to import a text file into R as a character vector -


i know if there's simple command in r exists , allow import char text file (.txt) char vector.

the file might english text string "hello name fagui curtain" , output in r char vector such a[1]<-"h", a[2]<-"e", a[3]<-"l", etc....

i've tried scan function, return words a[1]<-"hello", a[2]<-"my"....

i googled question couldn't find useful.

thanks

try strsplit after removing space gsub

a <- strsplit(gsub('\\s+', '', lines),'')[[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

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 using linux, scan , piped awk

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') 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -