修剪具有控制字符空格的字符串

时间:2017-07-12 07:48:22

标签: r trim

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

如何修剪 x 或任何具有未被 trimws 修剪的前导和/或尾随空格的类似字符串?

披露:这个问题是trimws bug? leading whitespace not removed的延续,但我被要求创建一个单独的问题。

编辑: 这是一个建议的代码,欢迎任何更优雅的解决方案

trimws2 = function(x) {
        sapply(x, FUN=function(x) {
          xraw = charToRaw(x)
          xraw[xraw==as.raw(0xa0)]=charToRaw(" ")
          trimws(rawToChar(xraw))
        })
      }
trimws2(x)

1 个答案:

答案 0 :(得分: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"