【问题标题】:R: Trim characters other than whitespace from a stringR:从字符串中修剪除空格以外的字符
【发布时间】:2019-06-19 10:05:31
【问题描述】:

在 R 中,如果您想从字符串末尾修剪所有空白字符,您可以使用 trimws(to.be.trimmed, "right"),如下所示:

> trimws("nauris        ", "right")
[1] "nauris"

如果我不想修剪空白字符,而是修剪句点(或其他一些字符)怎么办?在 Python 中,您可以使用 string.rstrip(char)。以下是一些期望的输出:

> rstrip("nauris", "s")
[1] "nauri"
> rstrip("nauris.", ".")
[1] "nauris"
> rstrip("nauris....", ".")
[1] "nauris"
> rstrip("stack", "c")
[1] "stack"

将所述句点作为最后一个参数不起作用,因为它只会返回一个空字符串:

trimws("nauris.", "right", ".")
[1] ""

【问题讨论】:

  • 每次修剪时总是相同的字符吗?该字符会出现在任何字符串的其他位置吗?
  • 为什么不使用gsub
  • gsub 也会从字符串中间删除这些字符,例如 gsub('\\c', '', "stack") 返回 "stak" 而不是 "stack"。跨度>

标签: r


【解决方案1】:

从 R 版本 3.6.0 trimws() 开始,您可以使用空格参数:

trimws("nauris", "right", whitespace = "s")
[1] "nauri"

trimws("nauris.....", "right", whitespace = "\\.")
[1] "nauris"

文档指出内部trimws() 使用sub(re, "", *, perl = TRUE),因此需要转义特殊字符。

【讨论】:

  • 值得一提的是,whitespace 参数自 R-3.6.0 起可用。
  • 那是什么版本?我收到关于未使用参数的错误
  • @tmfmnk - 谢谢。已更新帖子以包含其引入的版本。
【解决方案2】:

对于还没有更新R的人(比如我),可以复制trimws函数,根据我们的要求进行修改。

trim_periods <- function (x, which = c("both", "left", "right")) {
   which <- match.arg(which)
   mysub <- function(re, x) sub(re, "", x, perl = TRUE)
  if (which == "left") 
     return(mysub("^[.]+", x))
   if (which == "right") 
      return(mysub("[.]+$", x))
   mysub("[.]+$", mysub("^[.]+", x))
}

trim_periods("...abc..def..", "right")
#[1] "...abc..def"

trim_periods("...abc..def..")
#[1] "abc..def"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2023-01-04
    • 2010-09-16
    • 2010-10-20
    相关资源
    最近更新 更多