Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

perl

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

like image 280
CassJ Avatar asked Feb 06 '09 15:02

CassJ


6 Answers

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"
like image 85
hadley Avatar answered Nov 11 '22 16:11

hadley


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"    
like image 37
flodel Avatar answered Nov 11 '22 16:11

flodel


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>
like image 40
patrickmdnet Avatar answered Nov 11 '22 16:11

patrickmdnet


qw = function(s) unlist(strsplit(s,' '))
like image 21
Alex Zolot Avatar answered Nov 11 '22 16:11

Alex Zolot


Even simpler:

qw <- function(...){
as.character(substitute(list(...)))[-1]
}
like image 33
Ben Rollert Avatar answered Nov 11 '22 17:11

Ben Rollert


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]]
}
like image 1
Jerry T Avatar answered Nov 11 '22 17:11

Jerry T