Can R paste() output “\”?

后端 未结 3 1249
一整个雨季
一整个雨季 2020-12-18 10:41

As stated in the Intro to R manual,

paste(\"\\\\\")

prints

[1] \"\\\\\"

Is it possible for paste to prin

相关标签:
3条回答
  • 2020-12-18 11:02

    One way to do is is to use the write command, e.g.

    > write("\\", file="")
    \
    

    Write is usually used to write to files, so you need to set file="" to get it to print to STDOUT.

    The \ is repeated in the write command so that it doesn't escape the closing quotation mark.

    I'm not sure if this is the correct way to do it, but it works for me.

    Edit: Realised slightly too late that you were using the paste() command. Hopefully my answer still bears some relevance to your plight. Apologies.

    0 讨论(0)
  • 2020-12-18 11:14

    You are confusing how something is stored and how it "prints".

    You can use paste to combine a \ with something else, but if you print it then the printed representation will have \ to escape the \, but if you output it to a file or the screen using cat instead, then you get the single \, for example:

    > tmp <- paste( "\\", "cite{", sep="" )
    > print(tmp)
    [1] "\\cite{"
    > cat(tmp, "\n")
    \cite{ 
    
    0 讨论(0)
  • 2020-12-18 11:17

    That is the printed representation of a single "\" in R. Clearly the right answer will depend on your end usage, but will something like this do:

    > citations <- paste("title", 1:3, sep = "")
    > cites <- paste("\\citep{", citations, "}", sep = "")
    > writeLines(cites)
    \citep{title1}
    \citep{title2}
    \citep{title3}
    

    Using writeLines() you can output that to a file using something like:

    > writeLines(cites, con = file("cites.txt"))
    

    Resulting in the following file:

    $ cat cites.txt 
    \citep{title1}
    \citep{title2}
    \citep{title3}
    
    0 讨论(0)
提交回复
热议问题