简体   繁体   中英

Reading a string with special character in R

I have a little problem in reading a file in R. In particular, I run a script that load a file, say X, which stores a string per each line. There are string with special characters like, ' and therefore I get some errors.

I run the script by command line as follows

Rscript.exe MyScript.R "C:\X.txt"

The content of file X is, for instance:

I'll win a prize
I'll shutdown my pc

The MyScript.R script initially loads the file X.txt as follows

args <- commandArgs(TRUE)
args <- read.table(args[1], sep="\n")

and then uses it as follows:

print(nrow(args))

The previous line returns 0. However, if I remove the ' character from the two lines in file X.txt then everything works fine (ie, and the returned length is 2).

Any solution to handle this tricky input?

read.table is meant for reading structured data, ie data that is in the form of multiple fields per row. If you just want to read a bunch of strings, use readLines .

args <- readLines(args[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM