简体   繁体   中英

Replace \ into // using gsub in R

I am trying to replace x variable data E:\\testCSV.csv to E://testCSV.csv using gsub function..

> x
[1] "E:\testCSV.csv"
> gsub("\", "//", x, fixed = TRUE)
Error: unexpected '/' in "gsub("\", "//"

tried all combinations of escape strings, including brackets [] with no success. Please suggest

We may need

sub("^([^:]+\\:).(.*)", "\\1//t\\2", str1)
#[1] "E://testCSV.csv"

The reason it is not working is because t is escaped ie it represents for tab ( \\t ). To check it, we can use cat .

cat(str1, sep="\n")
#E:      estCSV.csv

Usually, we cannot create a string with a single \\ in R if it doesn't have any meaning.

str2 <- "E:\zestCV.csv"
#Error: '\z' is an unrecognized escape in character string starting ""E:\z"

We need to escape it with a second \\ .

str2 <- "E:\\zestCV.csv"
str2
#[1] "E:\\zestCV.csv"

To replace that, the method showed by the OP (slightly different) should work.

sub("\\\\", "//", str2)
#[1] "E://zestCV.csv"

data

str1 <-  "E:\testCSV.csv"

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