我的 trimws 怎么了?

what is going on with my trimws?

当我 运行 遇到一件有趣的事情时,我正在摆弄文本清理。

可重现代码:

trimws(list(c("this is an outrante", " hahaha", " ")))

输出:

[1] "c(\"this is an outrante\", \" hahaha\", \" \")"

我已经查看了 trimws 文档,除了它需要一个字符向量这一事实外,它没有涉及任何细节,在我的例子中,我已经提供了字符向量列表的列表。我知道我可以使用 lapply 轻松解决这个问题,但我想了解的是我的 trimws 是怎么回事?

trimws 将直接应用于 vector 而不是 list

根据?trimws文档,用法是

trimws(x, which = c("both", "left", "right"))

其中

x- a character vector

不清楚为什么 vector 被包裹在 list

trimws(c("this is an outrante", " hahaha", " "))

如果确实需要在 list 中,则使用进入 list 元素的函数之一并应用 trimws

lapply(list(c("this is an outrante", " hahaha", " ")), trimws)

此外,请注意 OP 的 list 是长度为 1 的 list,可以通过 [[1]] 或 [=29 将其转换回 vector =](更一般)

trimws(list(c("this is an outrante", " hahaha", " "))[[1]])

关于为什么一个函数会这样,它应该有一个输入参数作为 vector。该行为与其他需要 vector 的函数类似,例如

paste(list(c("this is an outrante", " hahaha", " ")))
as.character(list(c("this is an outrante", " hahaha", " ")))

如果我们检查 trimws 函数,它正在调用需要 vector

的正则表达式 sub
mysub <- function(re, x) sub(re, "", x, perl = TRUE) 
mysub("^[ \t\r\n]+", list(c("this is an outrante", " hahaha", " ")))
#[1] "c(\"this is an outrante\", \" hahaha\", \" \")"

传一个vector

mysub("^[ \t\r\n]+", c("this is an outrante", " hahaha", " "))
#[1] "this is an outrante" "hahaha"              ""