R: How to replace space (' ') in string with a *single* backslash and space ('\ ')

前端 未结 2 884
刺人心
刺人心 2020-12-19 00:54

I\'ve searched many times, and haven\'t found the answer here or elsewhere. I want to replace each space \' \' in variables containing file names with a \

2条回答
  •  执笔经年
    2020-12-19 01:17

    Get ready for a face-palm, because this:

    > gsub(" ", "\\\ ", "a b", fixed = TRUE)
    [1] "a\\ b"
    

    is actually working.

    The two backslashes you see are just the R console's way of displaying a single backslash, which is escaped when printed to the screen.

    To confirm the replacement with a single backslash is indeed working, try writing the output to a text file and inspect yourself:

    f <- file("C:\\output.txt")
    writeLines(gsub(" ", "\\", "a b", fixed = TRUE), f)
    close(f)
    

    In output.txt you should see the following:

    a\b
    

提交回复
热议问题