在R的替换命令中取消引用字符串

时间:2021-01-22 20:15:20

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

我想知道是否可以通过substitute命令取消引用传递给表达式的字符串。

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

具体来说,我使用dplyr来过滤并从数据框中进行选择:

    > 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.

但我想以更一般的方式做到这一点。以下内容不会产生所需的结果,因为字符串“sex”用引号括起来。

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

替代(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

1 个解决方案

#1


2  

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

基于@ hadley的评论

 eval(substitute(w%>% filter(y=="M"), list(y=as.name(names(w)[2]))))

#1


2  

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

基于@ hadley的评论

 eval(substitute(w%>% filter(y=="M"), list(y=as.name(names(w)[2]))))