Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing "/" into "\" in R

Tags:

r

backslash

slash

I need to change "/" into "\" in my R code. I have something like this:

tmp <- paste(getwd(),"tmp.xls",sep="/")

so my tmp is c:/Study/tmp.xls

and I want it to be: c:\Study\tmp.xls

Is it possible to change it in R?

like image 777
Ania Avatar asked Mar 26 '13 18:03

Ania


People also ask

How to change 0 to 1 in R?

To change the code “Yes” to 1, we can use ifelse function and set the Yes to 1 and others to 0. For example, if we have a data frame called df that contains a character column x which has Yes and No values then we can convert those values to 1 and 0 using the command ifelse(df$x=="Yes",1,0).

How do I change a number to text in R?

To convert number to words in an R data frame column, we can use english function from english package. For example, if we have a data frame called df that contains a number column x then we can convert the numbers into words by using the command as. character(english(df$x)).

Which R function can be used to make changes to a data frame?

transform() function in R Language is used to modify data. It converts the first argument to the data frame. This function is used to transform/modify the data frame in a quick and easy way.


Video Answer


1 Answers

Update as per comments.

If this is simply to save the file, then as @sgibb suggested, you are better off using file.path():

    file.path(getwd(), "tmp.xls") 

Update 2: You want double back-slashes.

tmp is a string and if you want to have an actual backslash you need to escape it -- with a backslash. However, when R interprets the double slashes (for example, when looking for a file with the path indicated by the string), it will treat the seemingly double slashes as one.

Take a look at what happens when you output the string with cat()

cat("c:\\Study\\tmp.xls")
c:\Study\tmp.xls

The second slash has "disappeared"


Original Answer:

in R, \ is an escape character, thus if you want to print it literally, you need to escape the escape character: \\. This is what you want to put in your paste statement.

You can also use .Platform$file.sep as your sep argument, which will make your code much more portable.

 tmp <- paste(getwd(),"tmp.xls",sep=.Platform$file.sep)

If you already have a string you would like to replace, you can use

    gsub("/", "\\", tmp, fixed=TRUE)
like image 143
Ricardo Saporta Avatar answered Sep 30 '22 07:09

Ricardo Saporta