[R] replace "%" with "\%"

(Ted Harding) Ted.Harding at manchester.ac.uk
Fri May 15 17:32:17 CEST 2009


On 15-May-09 14:46:27, Liviu Andronic wrote:
> Dear all,
> I'm trying to gsub() "%" with "\%" with no obvious success.
>> temp1 <- c("mean", "sd",   "0%",   "25%",  "50%",  "75%",  "100%")
>> temp1
> [1] "mean" "sd"   "0%"   "25%"  "50%"  "75%"  "100%"
>> gsub("%", "\%", temp1, fixed=TRUE)
> [1] "mean" "sd"   "0%"   "25%"  "50%"  "75%"  "100%"
> Warning messages:
> 1: '\%' is an unrecognized escape in a character string
> 2: unrecognized escape removed from "\%"
> 
> I am not quite sure on how to deal with this error message. I tried
> the following
>> gsub("%", "\\%", temp1, fixed=TRUE)
> [1] "mean"   "sd"     "0\\%"   "25\\%"  "50\\%"  "70\\%"  "100\\%"
> 
> Could anyone suggest how to obtain output similar to:
> [1] "mean"   "sd"     "0\%"   "25\%"  "50\%"  "75\%"  "100\%"
> 
> Thank you,
> Liviu

1: The double escape "\\" is the correct way to do it. If you
   give "\%" to gsub, it will try to interpret "%" as a special
   character (like "\n" for newline), and there is none such
   (as it tells you). On the other hand, "\\" tells gsub to
   interpret "\" (normally used as the Escape character) in a
   special way (namely as a literal "\").

2: The output
   "mean"   "sd"     "0\\%"   "25\\%"  "50\\%"  "70\\%"  "100\\%"
   from gsub("%", "\\%", temp1, fixed=TRUE) is one of those cases
   where R displays something different from what is really there!
   In other words, "0\\%" for example is the character string you
   would have to enter in order for R to store \%. You can see what
   is really there using cat:

     cat(gsub("%", "\\%", temp1, fixed=TRUE))
     # mean sd 0\% 25\% 50\% 75\% 100\%

   which, of course, is what you wanted. You can see in other ways
   that what is stored is what you wanted -- for instance:

     temp2 <- gsub("%", "\\%", temp1, fixed=TRUE)
     write.csv(temp2,"gsub.csv")

   and then, if you look into gsub.csv outside of R, you will see:

     "","x"
     "1","mean"
     "2","sd"
     "3","0\%"
     "4","25\%"
     "5","50\%"
     "6","75\%"
     "7","100\%"

   which, again, is what you wanted.

Hoping this helops,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 15-May-09                                       Time: 16:32:13
------------------------------ XFMail ------------------------------




More information about the R-help mailing list