Ignore escape characters (backslashes) in R string

2019-01-11 07:47发布

问题:

While running an R-plugin in SPSS, I receive a Windows path string as input e.g.

'C:\Users\mhermans\somefile.csv'

I would like to use that path in subsequent R code, but then the slashes need to be replaced with forward slashes, otherwise R interprets it as escapes (eg. "\U used without hex digits" errors).

I have however not been able to find a function that can replace the backslashes with foward slashes or double escape them. All those functions assume those characters are escaped.

So, is there something along the lines of:

>gsub('\\', '/', 'C:\Users\mhermans')
C:/Users/mhermans

回答1:

You can try to use the 'allowEscapes' argument in scan()

X=scan(what="character",allowEscapes=F)
C:\Users\mhermans\somefile.csv

print(X)
[1] "C:\\Users\\mhermans\\somefile.csv"


回答2:

First you need to get it assigned to a name:

pathname <- 'C:\\Users\\mhermans\\somefile.csv'

Notice that in order to get it into a name vector you needed to double them all, which gives a hint about how you could use regex:

 gsub("\\\\", "/", pathname)
# [1] "C:/Users/mhermans/somefile.csv"

You needed to doubly double the backslashes. The first of each couple of \'s is to signal to the grep machine that what nextcomes is a literal.



回答3:

If file E:\Data\junk.txt contains the following text (without quotes): C:\Users\mhermans\somefile.csv

You may get a warning with the following statement, but it will work:

 texinp <- readLines("E:\\Data\\junk.txt")

If file E:\Data\junk.txt contains the following text (with quotes): "C:\Users\mhermans\somefile.csv"

The above readlines statement might also give you a warning, but will now contain:

"\"C:\Users\mhermans\somefile.csv\""

So, to get what you want, make sure there aren't quotes in the incoming file, and use:

 texinp <- suppressWarnings(readLines("E:\\Data\\junk.txt"))