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)
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"