2
x = rawToChar(as.raw(c(0xa0, 0x31, 0x31, 0x2e, 0x31, 0x33, 0x32, 0x35, 0x39, 0x32)))
trimws(x) # this doesn't trim it!

How can I trim x or any similar string that has leading and/or trailing whitespace that are not trimmed by trimws?

Disclosure: this question is the continuation of trimws bug? leading whitespace not removed but I was asked to create a separate question.

Edit: here is a suggested code, any more elegant solution would be welcomed

trimws2 = function(x) {
        sapply(x, FUN=function(x) {
          xraw = charToRaw(x)
          xraw[xraw==as.raw(0xa0)]=charToRaw(" ")
          trimws(rawToChar(xraw))
        })
      }
trimws2(x)
RockScience
  • 17,932
  • 26
  • 89
  • 125
  • Your `x`gives me this : `[1] " 11.132592"`, you want to remove the space in front of the value ? – Mbr Mbr Jul 12 '17 at 08:04
  • @MbrMbr yes. But `trimws` doesn't work on my x. See https://stackoverflow.com/questions/45050617/trimws-bug-leading-whitespace-not-removed/45051137#45051137 – RockScience Jul 12 '17 at 08:04
  • 2
    @RockScience Did you try `str_trim` from the package `stringr` ? With my version of R (3.3.3), it returns : `[1] "11.132592"` – Mbr Mbr Jul 12 '17 at 08:06
  • @MbrMbr if you want to add this as answer, i will accept it asap. Thanks – RockScience Jul 12 '17 at 08:07
  • 1
    You weren't asked a separate question. @HongOoi said you didn't formulate your question well; which means you have to reformulate your question – Jaap Jul 12 '17 at 08:25

1 Answers1

4

Use str_trim from stringr package.

Data :

> x = rawToChar(as.raw(c(0xa0, 0x31, 0x31, 0x2e, 0x31, 0x33, 0x32, 0x35, 0x39, 0x32)))
> x
[1] " 11.132592"

and just write :

library(stringr)

str_trim(x)
[1] "11.132592"
Mbr Mbr
  • 734
  • 6
  • 23