在R的替代命令中取消引用字符串 [英] Unquote string in R's substitute command
问题描述
我想知道是否可以取消引用通过替代命令传递给表达式的字符串。
I'd like to know whether it is possible to unquote a string passed to an expression via the substitute command.
具体来说,我正在使用dplyr进行过滤并从数据框中选择:
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
但我想以更一般的方式执行此操作。由于字符串 sex用引号引起来,因此以下内容不会产生所需的结果。
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])))
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')")))
但这确实有点笨拙。
是否有更优雅的方法?最终,我想将其包装到一个函数中,并使其变得更通用。
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.
亲切的问候,
Stefan
推荐答案
也许您可以尝试:
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"))
基于@hadley的评论
Based on @hadley's comments
eval(substitute(w%>% filter(y=="M"), list(y=as.name(names(w)[2]))))
这篇关于在R的替代命令中取消引用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!