Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unquote string in R's substitute command

Tags:

r

dplyr

I'd like to know whether it is possible to unquote a string passed to an expression via the substitute command.

Specifically, I am using dplyr to filter and select from a data frame:

    > w
       subject sex response
    1        1   M    19.08
    2        2   M    16.46
    ...     ...  ...  ...
    6        6   M    23.60
    7        7   M    23.96
    8        8   F    22.48
    9        9   F    25.79
    ...     ...  ...  ...
    16      16   F    26.66

The following produces the desired result:

    > w %.% filter(sex == "M") %.% select(response)        
      response
    1    19.08
    2    16.46
    3    22.81
    4    18.62
    5    18.75
    6    23.60
    7    23.96

But I want to do this in a more general way. Th following does not produce the required result since the string "sex" is enclosed in quotation marks.

substitute(w %.% filter(y == "M"), list(y = paste(names(w)[2])))

    w %.% filter("sex" == "M")
    > eval(substitute(w %.% filter(y == "M"), list(y = paste(names(w)[2]))))
    [1] subject  sex      response
    <0 rows> (or 0-length row.names)

I can always do the following:

    eval(parse(text = paste("w %.% filter(", names(w)[2], " == 'M')")))

This does, however, look a little clumsy.

Are there more elegant ways of doing this? Eventually, I'd like to wrap this up in a function and make it even more general.

Any help / suggestion would be much appreciated.

Kind regards,

Stefan

like image 997
Stefan Avatar asked Jul 14 '14 08:07

Stefan


1 Answers

May be you can try:

w <- structure(list(subject = c(1L, 2L, 6L, 7L, 8L, 9L, 16L), sex = structure(c(2L, 
2L, 2L, 2L, 1L, 1L, 1L), .Label = c("F", "M"), class = "factor"), 
response = c(19.08, 16.46, 23.6, 23.96, 22.48, 25.79, 26.66
)), .Names = c("subject", "sex", "response"), class = "data.frame", row.names = c("1", 
"2", "6", "7", "8", "9", "16"))

Based on @hadley's comments

 eval(substitute(w%>% filter(y=="M"), list(y=as.name(names(w)[2]))))
like image 141
akrun Avatar answered Sep 17 '22 11:09

akrun