在R的替换命令中取消引用字符串
我想知道是否可以通过replacement命令对传递给表达式的字符串进行解压缩 具体而言,我使用dplyr从数据帧中筛选和选择:在R的替换命令中取消引用字符串,r,dplyr,R,Dplyr,我想知道是否可以通过replacement命令对传递给表达式的字符串进行解压缩 具体而言,我使用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
> 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包含在引号中,因此以下内容不会生成所需的结果
substitutew%。%filtery==M,listy=pastenamesw[2]
然而,这看起来确实有点笨拙
还有更优雅的方法吗?最后,我想把它包装成一个函数,使它更加通用
如有任何帮助/建议,将不胜感激
亲切问候,
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"))
+1.如果您想使用我即将发布的示例进行更新,您可以使用mtcars%>%filtergetpastenamesmtcars[2],envir=as.environmentmtcars==4%>%selectmpg:-@Ananda Mahto,谢谢。我用帖子中显示的数据集进行了更新。我想不需要浆糊。这不是——我想我只是在翻译OP的方法,并没有真正注意:-谢谢@AnandaMahto和akun,这非常有效。这是一个非常脆弱的方法。类似的问答尝试as.name谢谢,直到akrun在回答中使用它,我才知道as.name。
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"))
eval(substitute(w%>% filter(y=="M"), list(y=as.name(names(w)[2]))))