How do I replace \(escape) with / in the path?

Asked 1 years ago, Updated 1 years ago, 44 views

I would like to replace the (escape) of the specified path with / when the path was specified.
For example
C:\R\data\covid

C:/R/data/covid/
I would like to replace it like this.

I tried to replace the path with // using the gsub function as shown in the program below, but I got an error.

gsub("\\", "/", "C:\R\data\covid\")
Error: '\R' is an escape that is not recognized by the string in the string beginning with 'C:\R' 

Is there a way to replace the third variable without rewriting it?(I think the reason for the error is (escape) in the third variable, but I want to use the third variable as it is.)

Supplemental
The following programs have been verified to work:

gsub("\\", "/", "C:\\R\\data\\covid\\", fixed=TRUE)
[1] "C:/R/data/covid/"
gsub("\\\", "/", "C:\\R\\data\\covid\\")
[1] "C:/R/data/covid/"

r regular-expression

2022-09-29 22:09

1 Answers

In R languages (e.g., non-R languages and C languages), backslash means escape sequence.
The backslash itself has a special meaning.
Therefore, if you want to express \\, you can use two words: \\.
This means "\" in the program.
Therefore,

gsub("\\", "/", "C:\\R\\data\\covid\\", fixed=TRUE)
[1] "C:/R/data/covid/"
gsub("\\\", "/", "C:\\R\\data\\covid\\")
[1] "C:/R/data/covid/"

If you write "\\" as shown in , it is considered "\" internally, so this is correct.


2022-09-29 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.