How can I substitute double backslashes for single backslashes? - r

Example:
example <- "\\begin"
example <- gsub(pattern = "\\\\", replacement = "\\", example)
I know the backslashes need to be escaped, which is why they're duplicated in the gsub function. But this code returns the string "begin" devoid of any backslashes. I've also tried
example <- "\\begin"
example <- gsub(pattern = "\\", replacement = "\", example, fixed = TRUE)
But RStudio (and apparently StackOverflow!) really doesn't like that--it treats "" like an open quotation mark followed by an escaped close quotation mark, rather than treating it as a string of a single backslash.
How can I do this? For better context, I have a .txt file of .tex code (except that every backslash is duplicated) that I am trying to turn into a .tex file within an Rmd document.
I'd be happy to use an implementation using stringr, if that makes things easier.

Related

How to encode strings in R with double backslashes?

Is there any easy way in R to encode strings with double backslashes?. I extracted some data from a website and realised that words in the data were decoded. The following is part of the data:
'"option_name\":\"\\uc81c\\ud488\\uc120\\ud0dd#$%\\uc0c9\\uc0c1\"'
I want it to be:
'"option_name":"제품선택#$%색상"'
If I manually replace double backslashes from the string and print, it works fine but I want to avoid manual work with this. It would be great if someone could help me with this issue?
Given the example provided, it does not appear to have "double backslashes" -- perhaps you mean double quotes?
In either case, the string on the right of the colon is in Unicode, so something like this will encode correctly:
string <- "\uc81c\ud488\uc120\ud0dd#$%\uc0c9\uc0c1"
new_string <- enc2utf8(string)
cat(new_string)
"제품선택#$%색상"
If you want to treat the entire selection as one string, you can wrap it in single quotes:
string <- '"option_name":"\uc81c\ud488\uc120\ud0dd#$%\uc0c9\uc0c1"'
new_string <- enc2utf8(string)
cat(new_string)
"option_name":"제품선택#$%색상"
# to remove the double quotes at the same time:
new_string <- gsub('\"', "", enc2utf8(string))
cat(new_string)
option_name:제품선택#$%색상

How can I replace "map-09" by `map-09` in R? (from double quotes to single quotes)

I tried with gsub, and str_replace, but I didn't get what I need.
gsub("\"", "\`", "map-09", fixed=TRUE)
gives "map-09" and not map-09
str_replace("map-09","\"","\`")
gives "map-09" and not map-09
I think you're getting confused between the way the string is being represented vs. what the string actually is. The functions you're using don't actually add any quotes. But when the output is printed quotes are there to show you that it is a string being represented. If you use the function 'cat' to print the output you'll see it without the quotes.
See the difference between
print("example")
cat("example")

R with gsub() instead ' of \'

I want let a string like "ab'" become "ab\'"
I have tried following code
aa="ab'"
aa<-gsub("'","\\'",aa)
show ab'
aa="ab'"
aa<-gsub("'","\\\'",aa)
show ab'
aa="ab'"
aa<-gsub("'","\\\\'",aa)
show ab\\'
I don't know how to fixed it
please give me some suggest
In the case of the following code:
aa <- "ab'"
aa <- gsub("'", "\\\\'", aa)
In fact you are replacing a single quote with a single literal backslash. The output you see ab\\' I believe just shows an extra backslash to let you know that it is not an escape character.
Consider the following extension of your code:
gsub("\\\\", "A", gsub("'","\\\\'",aa))
[1] "abA'"
We can clearly see that there is only a single A in the replacement, implying that there was only a single backslash to be replaced.
Even though on the terminal, you sometimes see "\\" it is actually just "\".
Print the result using writeLines() to see the actual string:
> original_string = "ab'"
> new_string = gsub("'","\\\\",original_string)
> writeLines(new_string)
ab\
Bonus funny: https://xkcd.com/1638/

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.

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