【问题标题】:Does R have quote-like operators like Perl's qw()?R 是否有像 Perl 的 qw() 这样的类似引号的运算符?
【发布时间】:2010-10-05 23:15:39
【问题描述】:

有人知道 R 是否有像 Perl 的 qw() 这样的类似引号的运算符来生成字符向量?

【问题讨论】:

    标签: r perl


    【解决方案1】:

    没有,但你可以自己写:

    q <- function(...) {
      sapply(match.call()[-1], deparse)
    }
    

    只是为了证明它有效:

    > q(a, b, c)
    [1] "a" "b" "c"
    

    【讨论】:

    • 这似乎不再起作用了。当我在我的 Rstudio 控制台中运行该示例时,它只是挂起。
    • @hadley 如果我希望它与中间的逗号一起打印怎么办?
    【解决方案2】:

    我已将此功能添加到我的 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"    
    

    【讨论】:

    • 当你第一次发布这个答案时,我把它放在了一个个人包里,我一直在使用它。这很棒。谢谢。
    【解决方案3】:

    流行的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>
    

    【讨论】:

      【解决方案4】:
      qw = function(s) unlist(strsplit(s,' '))
      

      【讨论】:

        【解决方案5】:

        更简单:

        qw <- function(...){
        as.character(substitute(list(...)))[-1]
        }
        

        【讨论】:

          【解决方案6】:

          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]]
          }
          

          【讨论】:

            猜你喜欢
            • 2017-07-24
            • 1970-01-01
            • 1970-01-01
            • 2011-10-14
            • 2017-06-03
            • 1970-01-01
            • 2012-11-25
            相关资源
            最近更新 更多