0

I have an issue creating a string with a special character. I have asked a similar question and I have also read answers to similar questions about my problem but I am not able to find the solution.

I want to create a string character with a special character. I have been trying with cat but I know it is only for printing, not for saving the string in a variable in R.

I want as a result this:

> cat("C:\\Users\\ppp\\ddd\\")
C:\Users\ppp\ddd\

and I have been trying with paste and collapse but without success:

> x = c("C:","Users","ppp","ddd")
> t <- paste0(x, collapse = '\n')
> t
[1] "C:\nUsers\nppp\nddd"
dan1st
  • 12,568
  • 8
  • 34
  • 67
Sss
  • 427
  • 2
  • 8
  • you should use `file.path` and not `paste`: `file.path("C:","Users","ppp","ddd")` – rawr May 27 '21 at 17:41
  • I do not want a working directory for R. I want to create a string. – Sss May 27 '21 at 17:44
  • that's what it does – rawr May 27 '21 at 17:45
  • yes, but to create a string with this \ as separation, not this / – Sss May 27 '21 at 17:48
  • 1) `/` works on windows, 2) `file.path` will chose the correct default separator for your OS, that is one reason it is superior to `paste`, 3) you can override the default separator, you should read the help file for `?file.path` – rawr May 27 '21 at 17:50
  • I do not want to create a file.path. I want to save the string and after import in Matlab that for the file paths use \ instead of / – Sss May 27 '21 at 17:55
  • _a file path is a string is a file path is a string_ – rawr May 27 '21 at 18:02

2 Answers2

1

Are you sure you don't want

x = c("C:","Users","ppp","ddd")
t <- paste0(x, collapse = '/')
t
[1] "C:/Users/ppp/ddd"

R uses this format for setting working directories.

You can also do:

x = c("C:","Users","ppp","ddd")
t <- paste0(x, collapse = '\\')
t
[1] "C:\\Users\\ppp\\ddd"

Although this result looks wrong, if you are using the string in a shell() command in R to be interpreted Windows for example, it will be interpreted correctly

  • I know how the working directory works in R, but I want in the way I explained for MATLAB – Sss May 27 '21 at 17:43
  • If it's going to MATLAB can't you store it in a way that works in R, and then change it in your MATLAB code? –  May 27 '21 at 18:04
0

Not Answering... but

t <- paste0(x, collapse = '/')

"C:/Users/ppp/ddd" seems to work on windows.