【发布时间】:2010-10-05 23:15:39
【问题描述】:
有人知道 R 是否有像 Perl 的 qw() 这样的类似引号的运算符来生成字符向量?
【问题讨论】:
有人知道 R 是否有像 Perl 的 qw() 这样的类似引号的运算符来生成字符向量?
【问题讨论】:
没有,但你可以自己写:
q <- function(...) {
sapply(match.call()[-1], deparse)
}
只是为了证明它有效:
> q(a, b, c)
[1] "a" "b" "c"
【讨论】:
我已将此功能添加到我的 Rprofile.site 文件中(如果您不熟悉,请参阅 ?Startup)
qw <- function(x) unlist(strsplit(x, "[[:space:]]+"))
qw("You can type text here
with linebreaks if you
wish")
# [1] "You" "can" "type" "text"
# [5] "here" "with" "linebreaks" "if"
# [9] "you" "wish"
【讨论】:
流行的Hmisc package 提供函数Cs() 来执行此操作:
library(Hmisc)
Cs(foo,bar)
[1] "foo" "bar"
它使用与哈德利的回答类似的策略:
Cs
function (...)
{
if (.SV4. || .R.)
as.character(sys.call())[-1]
else {
y <- ((sys.frame())[["..."]])[[1]][-1]
unlist(lapply(y, deparse))
}
}
<environment: namespace:Hmisc>
【讨论】:
qw = function(s) unlist(strsplit(s,' '))
【讨论】:
更简单:
qw <- function(...){
as.character(substitute(list(...)))[-1]
}
【讨论】:
sn-p 适用于传入向量的情况,例如,v=c('apple','apple tree','apple cider'). You would get c('"apple"','"apple tree"','"apple cider"')
quoted = function(v){
base::strsplit(paste0('"', v, '"',collapse = '/|||/'), split = '/|||/',fixed = TRUE)[[1]]
}
【讨论】: