Replacing Backward slash in R - r

I want to replace backward slashes with forwards slashes in a string. So I used below syntax in R.
stringr::str_replace("\\", "//", "\\asd")
However it fails to replace the backward slashes in the given string.
Could you please help to find the right way to replace them?
I am using R in Windows 10 machine

Try this:
str_replace("\\asd", fixed("\\"), "//")

You have the arguments in the wrong order and you need to escape the backslashes.
> stringr::str_replace("\\asd", "\\\\", "//")
[1] "//asd"

You could use gsub function in R which is used for replacement operations. The functions takes the input and substitutes it against the specified value.
gsub("\\\\", "/", x)

Related

Convert backslash to forward slash in R non-interactively

I'm trying to take an input path and convert the slashes from backwards to forwards as part of an R package. There are some suggestions to do this here and elsewhere, but all of these solutions require some amount of interaction by the user: either copying a path, or selecting a path from a prompt. I would be happy if I could find a solution that works on strings, but when I try to use strings with slashes in R, I run into problems.
# example path
path <- "C:\aaa\bbb\fff\"\n" # I have to add this \n linebreak for R to save the object without an error
# replace slashes in string
gsub(pattern="\"", replacement="/", x=path) # I have to put an extra quote in the pattern to avoid error, but this makes it not work.
Note that to avoid errors in this example, I had to save the path with a linebreak and there is an extra quote in the pattern for gsub. This is only a problem on Windows computers, but I need my package to work on Windows. Thanks in advance for suggestions.

How to replace backslash \ in R with gsub?

I would like to ammend some .tex files from within R.
I read the file with readLines() but I cannot replace the following text.
tex <- "$\\times$"
new_tex <- gsub("$\\times$", "\\ $\\times$", tex)
new_tex
It seems that it cannot find the $\\times$
But even if it does, is it possible to write \ without escaping them?
Thank you in advance!
gsub uses regular expressions by default unless you set fixed=TRUE.
In regular expressions $ means the end of the sentence , that's why it does not work.
This, instead should work :
new_tex <- gsub("$\\times$", "\\ $\\times$", tex,fixed=TRUE)
About the backslash, no, you can't write a backslash without escaping it. Otherwise, for example, it would be impossible for the R interpreter, to distinguish between a tab \t and a "backslash + t".
Without fixed = TRUE:
gsub("\\$\\\\times\\$", "\\\\ $\\\\times\\$", tex)
[1] "\\ $\\times$"
Unfortunately you need a lot of backslashes because you need to escape pretty much everything.

substitute single backslash in R

I have read some questions and answers on this topic in stack overflow but still don't know how to solve this problem:
My purpose is to transform the file directory strings in windows explorer to the form which is recognizable in R, e.g. C:\Users\Public needs to be transformed to C:/Users/Public, basically the single back slash should be substituted with the forward slash. However the R couldn't store the original string "C:\Users\Public" because the \U and \P are deemed to be escape character.
dirTransformer <- function(str){
str.trns <- gsub("\\", "/", str)
return(str.trns)
}
str <- "C:\Users\Public"
dirTransformer(str)
> Error: '\U' used without hex digits in character string starting ""C:\U"
What I am actually writing is a GUI, where the end effect is, the user types or pastes the directory into a entry field, pushes a button and then the program will process it automatically.
Would someone please suggest to me how to solve this problem?
When you need to use a backslash in the string in R, you need to put double backslash. Also, when you use gsub("\\", "/", str), the first argument is parsed as a regex, and it is not valid as it only contains a single literal backslash that must escape something. In fact, you need to make gsub treat it as a plain text with fixed=TRUE.
However, you might want to use normalizePath, see this SO thread.
dirTransformer <- function(str){
str.trns <- gsub("\\\\", "/", str)
return(str.trns)
}
str <- readline()
C:\Users\Public
dirTransformer(str)
I'm not sure how you intend the user to input the path into the GUI, but when using readline() and then typing C:\Users\Public unquoted, R reads that in as:
> str
[1] "C:\\Users\\Public"
We then want to replace "\\" with "/", but to escape the "\\" we need "\\\\" in the gsub.
I can't be sure how the input from the user is going to be read into R in your GUI, but R will most likely escape the \s in the string like it does when using the readline example. the string you're trying to create "C:\Users\Public" wouldn't normally happen.

How to extract specific characters in R String

I have a file name string:
directoryLocation<-"\Users\me\Dropbox\Work\"
How can I extract all the "\" and replace it with "\"? In other languages, you can loop through the string and then replace character by character, but I don't think you can do that in R.
I tried
substr(directoryLocation,1,1)
but it is highly optimized to this case...how can it be more general?
Thanks
gsub is the general tool for this, but as others have noted you need a confusing four slashes to account for the escapes: you need to escape for both R text and the regexp engine simultaneously.
An alternative, if using Windows, is to use normalizePath and setting the winslash parameter:
normalizePath(directoryLocation,winslash="/",mustWork=FALSE)
[1] "C:/Users/me/Dropbox/Work/"
Though this may perform additional work on expanding relative paths to absolute ones (seen here by prepending with C:).
In theory this would do what you want
gsub("\\\", "/", directoryLocation)
however...
R> directoryLocation<-"\\Users\\me\\Dropbox\\Work\\"
R> directoryLocation
[1] "\\Users\\me\\Dropbox\\Work\\"
R> gsub("\\\\", "/", directoryLocation)
[1] "/Users/me/Dropbox/Work/"
At least on windows one needs to escape all of the backslashes, but gsub is what you want.
gsub("\\\\","/","\\Users\\me\\Dropbox\\Work\\")
[1] "/Users/me/Dropbox/Work/"

Changing "/" into "\" in R

I need to change "/" into "\" in my R code. I have something like this:
tmp <- paste(getwd(),"tmp.xls",sep="/")
so my tmp is c:/Study/tmp.xls
and I want it to be: c:\Study\tmp.xls
Is it possible to change it in R?
Update as per comments.
If this is simply to save the file, then as #sgibb suggested, you are better off using file.path():
file.path(getwd(), "tmp.xls")
Update 2: You want double back-slashes.
tmp is a string and if you want to have an actual backslash you need to escape it -- with a backslash.
However, when R interprets the double slashes (for example, when looking for a file with the path indicated by the string), it will treat the seemingly double slashes as one.
Take a look at what happens when you output the string with cat()
cat("c:\\Study\\tmp.xls")
c:\Study\tmp.xls
The second slash has "disappeared"
Original Answer:
in R, \ is an escape character, thus if you want to print it literally, you need to escape the escape character: \\. This is what you want to put in your paste statement.
You can also use .Platform$file.sep as your sep argument, which will make your code much more portable.
tmp <- paste(getwd(),"tmp.xls",sep=.Platform$file.sep)
If you already have a string you would like to replace, you can use
gsub("/", "\\", tmp, fixed=TRUE)

Resources