Paste "25 \%" in R for further processing in LaTeX - r

I want a character variable in R taking the value from, lets say "a", and adding " \%", to create a %-sign later in LaTeX.
Usually I'd do something like:
a <- 5
paste(a,"\%")
but this fails.
Error: '\%' is an unrecognized escape in character string starting "\%"
Any ideas? A workaround would be to define another command giving the %-sign in LaTeX, but I'd prefer a solution within R.

As many other languages, certain characters in strings have a different meaning when they're escaped. One example for that is \n, which means newline instead of n. When you write \%, R tries to interpret % as a special character and fails doing so. You might want to try to escape the backslash, so that it is just a backslash:
paste(a, "\\%")
You can read on escape sequences here.

You can also look at the latexTranslate function from the Hmisc package, which will escape special characters from strings to make them LaTeX-compatible :
R> latexTranslate("You want to give me 100$ ? I agree 100% !")
[1] "You want to give me 100\\$ ? I agree 100\\% !"

Related

Unable to enclose double quotes inside string in R

unable to enclose "hey" in double quotes within a string . I am unable to get output as Hey "Hey"
ad<- "hey"
fd<- paste("Hey","",ad,sep="")
The dQuote function is made for this:
dQuote("hey")
# [1] "\"hey\""
Note that depending on the OS and your environment, it might add "fancy quotes" (angled/directional double-quotes). They may look good but if you want to reuse the results as a string in R, it won't work because R does not recognize its smart quotes as string-boundaries. You can explicitly disable it with dQuote(., q=FALSE). (The default is FALSE on windows except for the Rgui console, but I believe the default is TRUE elsewhere.)
Depending on your need, you may also like shQuote due to its escaping of existing embedded quotes:
cat(dQuote('"hey" there'), "\n")
# ""hey" there" # may not be right
cat(shQuote('"hey" there'), "\n")
# "\"hey\" there"
though whether that is correct depends on your needs; shQuote was designed for shell-quoting/escaping.
Ultimately in your example, I think you would use
ad <- "Hey"
paste("Hey", dQuote(ad))
# [1] "Hey \"Hey\""
Double quotes can be added with
paste0('"', "Hey", '"')
#[1] "\"Hey\""
Or
sprintf('"%s"', "Hey")
#[1] "\"Hey\""
Note that R displays strings with double quotes (") so to show double quotes as part of string it escapes it with backslash \. To see actual string you may use cat on it.
cat(paste0('"', "Hey", '"'))
#"Hey"
You can write raw strings like:
r"{"Hey"}"
r'{"Hey"}'
[1] "\"hey\""
See ?Quotes
Raw character constants are also available using a syntax similar to the one used in C++: r"(...)" with ... any character sequence, except that it must not contain the closing sequence )". The delimiter pairs [] and {} can also be used, and R can be used in place of r. For additional flexibility, a number of dashes can be placed between the opening quote and the opening delimiter, as long as the same number of dashes appear between the closing delimiter and the closing quote.

How to remove "\" from paste function output with quotation marks?

I'm working with the following code:
Y_Columns <- c("Y.1.1")
paste('{"ImportId":"', Y_Columns, '"}', sep = "")
The paste function produces the following output:
"{\"ImportId\":\"Y.1.1\"}"
How do I get the paste function to omit the \? Such that, the output is:
"{"ImportId":"Y.1.1"}"
Thank you for your help.
Note: I did do a search on SO to see if there were any Q's that asked "what is an escape character in R". But I didn't review all the 160 answers, only the first 20.
This is one way of demonstrating what I wrote in my comment:
out <- paste('{"ImportId":"', Y_Columns, '"}', sep = "")
out
#[1] "{\"ImportId\":\"Y.1.1\"}"
?print
print(out,quote=FALSE)
#[1] {"ImportId":"Y.1.1"}
Both R and regex patterns use escape characters to allow special characters to be displayed in print output or input. (And sometimes regex patterns need to have doubled escapes.) R has a few characters that need to be "escaped" in certain situation. You illustrated one such situation: including double-quote character inside a result that will be printed with surrounding double-quotes. If you were intending to include any single quotes inside a character value that was delimited by single quotes at the time of creation, they would have needed to be escaped as well.
out2 <- '\'quoted\''
nchar(out2)
#[1] 8 ... note that neither the surround single-quotes nor the backslashes get counted
> out2
[1] "'quoted'" ... and the default output quote-char is a double-quote.
Here's a good Q&A to review:How to replace '+' using gsub() function in R
It has two answers, both useful: one shows how to double escape a special character and the other shows how to use teh fixed argument to get around that requirement.
And another potentially useful Q&A on the topic of handling Windows paths:
File path issues in R using Windows ("Hex digits in character string" error)
And some further useful reading suggestions: Look at the series of help pages that start with capital letters. (Since I can never remember which one has which nugget of essential information, I tried ?Syntax first and it has a "See Also" list of essential reading: Arithmetic, Comparison, Control, Extract, Logic, NumericConstants, Paren, Quotes, Reserved. and I then realized what I wanted to refer you to was most likely ?Quotes where all the R-specific escape sequence letters should be listed.

How to just remove (\) from string with (\") while keeping (")?

Since special characters are inevitable while working data from excel.
There are so many links to eradicate special characters but when trying to remove \, we got to use \" which will eliminate both
Remove quotes ("") from a data.frame in R
Here, they remove both quotes but quotes at the end needs to be present.
> abc = c("Hi\"","Hello\\")
> abc
[1] "Hi\"" "Hello\\"
> str_replace_all(abc, "\"","")
[1] "Hi " "Hello\\"
But can we have
Hi" as an output ?
#Ronak Shah, #Chelmy88 and #Konrad Rudolph
helped me to understand where I was wrong in interpretation.
basically, it has to do with the way R renders the string in console.
Solution using cat() can resolve the confusion.

Nesting more than two types of quotes in R

I would like to know how to accommodate more than two types of quotes in a same row in R. Let´s say that I want to print:
'first-quote-type1 "first-quote-type2 "second-quote-type2
'sencond-quote-type1
Using one quote in the beginning and one in the end we have:
print("'first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1")
Error: unexpected symbol in "print("'first-quote-type1 "first"
I tried to include triple quotes as required in Python in this cases:
print(''''first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1''')
print("""'first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1""")
However, I also got a similar error. Some idea how to make this syntax work in R?
To use a quote within a quote you can escape the quote character with a backslash
print("the man said \"hello\"")
However, the print function in R will always escape character.
To not show the escaped character use cat() instead
so...
cat("the man said \"hello\"") will return
the man said "hello"

Using non-ASCII characters inside functions for packages

I'm trying to write a function equivalent to scales::dollar that adds a pound (£) symbol to the beginning of a figure. Since the scales code is so robust, I've used it as a framework and simply replaced the $ for the £.
A stripped-down function example:
pounds<-function(x) paste0("£",x)
When I run a CHECK I get the following:
Found the following file with non-ASCII characters:
pounds.R
Portable packages must use only ASCII characters in their R code,
except perhaps in comments.
Use \uxxxx escapes for other characters.
Looking through the Writing R extensions guide it doesn't give a lot of help (IMO) on how to resolve this issue. It mentions the \uxxxx and says it refers to Unicode characters.
Looking up unicode characters yields me the code &#163 but the guidance I can find for \uxxxx is minimal and relates to Java on W3schools.
My question is thus:
How do you implement the usage of non-unicode characters in R functions using the \uxxxx escapes and how does the usage affect the display of such characters after the function has been used?
For the \uxxxx escapes, you need to know the hexadecimal number of your character. You can determine it using charToRaw:
sprintf("%X", as.integer(charToRaw("£")))
[1] "A3"
Now you can use this to specify your non-ascii character. Both \u00A3 and £ represent the same character.
Another option is to use stringi::stri_escape_unicode:
library(stringi)
stringi::stri_escape_unicode("➛")
# "\\u279b"
This informs you that "\u279b" represents the character "➛".
Try this:
pounds<-function(x) paste0("\u00A3",x)
The stringi package can be useful is these situations:
library(stringi)
stri_escape_unicode("£")
#> [1] "\\u00a3"

Resources