CassJ
CassJ

Reputation: 253

Does R have quote-like operators like Perl's qw()?

Anyone know if R has quote-like operators like Perl's qw() for generating character vectors?

Upvotes: 23

Views: 6837

Answers (6)

Jerry T
Jerry T

Reputation: 1690

a snippet working for the case where a vector is passed in, eg., 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]]
}

Upvotes: 1

Ben Rollert
Ben Rollert

Reputation: 1584

Even simpler:

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

Upvotes: 3

flodel
flodel

Reputation: 89067

I have added this function to my Rprofile.site file (see ?Startup if you are not familiar)

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"    

Upvotes: 11

patrickmdnet
patrickmdnet

Reputation: 3392

The popular Hmisc package offers the function Cs() to do this:

library(Hmisc)
Cs(foo,bar)
[1] "foo" "bar"

which uses a similar strategy to hadley's answer:

Cs
function (...) 
{
    if (.SV4. || .R.) 
        as.character(sys.call())[-1]
    else {
        y <- ((sys.frame())[["..."]])[[1]][-1]
        unlist(lapply(y, deparse))
    }
}
<environment: namespace:Hmisc>

Upvotes: 8

Alex Zolot
Alex Zolot

Reputation: 51

qw = function(s) unlist(strsplit(s,' '))

Upvotes: 5

hadley
hadley

Reputation: 103898

No, but you can write it yourself:

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

And just to show it works:

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

Upvotes: 26

Related Questions