Problem with escape character in paste-function in R

I am trying to paste together a path-string. Like this C:\testfile.txt

This doesn't work at all:

filename - testfile.txt

path - paste(C:\\\,filename,sep=)

This also doesn't produce the right result:

filename - testfile.txt

path - paste(C:\\\\,filename,sep=)

[1] C:\\\testfile.txt

Can you help me to prudece a path-string with only one backslash?

Topic pasting r

Category Data Science


This works:

> paste("C:\\",filename,sep="")
[1] "C:\\testfile.txt"

Although you see TWO backslashes, there's really only one there, because usually when printed a backslash means "the next character is encoding a special character". In this case the special character is literally a backslash.

You can see this by counting the number of characters in two backslashes:

> nchar("\\")
[1] 1

And anyway you should probably be using file.path to construct paths and not fiddling around with backslashes:

> file.path("C:",filename)
[1] "C:/testfile.txt"

(Note forward slashes here also work in Windows and don't suffer from having to be backslash-encoded).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.