Maya Gosztyla
Maya Gosztyla

Reputation: 107

How to remove double backslash from each element of a vector?

I have a vector containing a bunch of file paths, like this:

 v <- paste0("D:\\file\\path", 1:3)

I want to replace all the double backslashes with just a single backslash. So the output would look like this:

"D:\file\path1" "D:\file\path2" "D:\file\path3"

I tried this:

sapply(df, cat)

However this just generates a list of NULL values. I also tried:

for (i in 1:length(v)) {
    v[i] <- cat(v[i])
}

But this gives an error: replacement has zero lengths. I'm not sure what I'm doing wrong.

Upvotes: 1

Views: 1193

Answers (1)

Bastien
Bastien

Reputation: 166

The \ is an escape character in R, thus replacing \\ by \ will cause wrong interpretation from R.

If the need is for paths, use the / character instead of \\:

v <- gsub(v, pattern="\\", replacement="/", fixed=TRUE)

Upvotes: 3

Related Questions