有人知道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包提供了函数Cs()
来实现这一功能:
library(Hmisc)
Cs(foo,bar)
[1] "foo" "bar"
这里使用了类似于Hadley的答案的方法:
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]
}
以下代码片段适用于传入向量的情况,例如:v=c('apple','apple tree','apple cider')。你将得到c('"apple"','"apple tree"','"apple cider"')
quoted = function(v){
base::strsplit(paste0('"', v, '"',collapse = '/|||/'), split = '/|||/',fixed = TRUE)[[1]]
}