gpt4 book ai didi

r - R的替代命令中的取消引号字符串

转载 作者:行者123 更新时间:2023-12-04 08:48:47 25 4
gpt4 key购买 nike

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

具体来说,我正在使用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

以下将产生期望的结果:
    > 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”用引号引起来,因此无法产生所需的结果。

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)

我总是可以做到以下几点:
    eval(parse(text = paste("w %.% filter(", names(w)[2], " == 'M')")))

但是,这看起来有点笨拙。

有没有更优雅的方法可以做到这一点?最终,我想将其包装在一个函数中并使其更加通用。

任何帮助/建议将不胜感激。

亲切的问候,

斯特凡

最佳答案

也许您可以尝试:

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的评论
 eval(substitute(w%>% filter(y=="M"), list(y=as.name(names(w)[2]))))

关于r - R的替代命令中的取消引号字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24732838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com