Auto quote in R

Sometimes I have to make a character vector in R. Say for renaming the columns of a matrix. In which case, I have to laboriously type quotes around each of the names. I know it’s only a minor irritation, but wouldn’t it be nicer if they could be quoted for you? Like in Perl where you can do

[perl]
@foo =qw(one two three);
[/perl]

Stack Overflow (thanks hadley) suggested:

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

Which works, but I can’t quite figure out why. I’ve had a look at the R language definition docs and as far as I can tell match.call returns a call object – essentially a vector in which the first entry is the function call and the rest are the args. deparse turns an unevaluated R expression into a string. But I don’t quite understand how it’s working in the above code. if I do:

[text]
qw<-function(…){
deparse(match.call()[2])
}
qw(a,b,c)
[/text]

I get

[text]
[1] "a()"
[/text]

rather than “a”. I think sapply is actually coercing the call object to a character vector, in which case, I’m not sure the call to deparse is actually necessary. This seems to work:

[text]
qw <- function(…) {
as.character(sys.call()[-1])
}
qw(a,b,c)

[1] "a" "b" "c"
[/text]

Still not strictly like Perl’s qw which doesn’t need the commas. I really want to be able to do qw(a b c) but I can’t figure out how to do it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s