[英]passing column name as variable in dplyr
Variants of this question have been asked a lot, I also read about NSE. 这个问题的变体已经问了很多,我也读过有关NSE的文章。 Still I cannot figure this out.
我仍然无法弄清楚。
This is easy: 这很容易:
library(dplyr)
data(cars)
cars %>%
group_by(speed) %>%
summarise(d = mean(dist))
Now I want to use variable x to pass the dist column to mean 现在我想使用变量x传递dist列来表示
x <- "dist"
Of course this does not work: 当然这是行不通的:
cars %>%
group_by(speed) %>%
summarise(d = mean(x))
So I use SE version of summarise: 所以我使用SE版本的摘要:
cars %>%
group_by(speed) %>%
summarise_(d = mean(x))
Ok, does not work, so I have to add ~
as well: 好的,这行不通,所以我还必须添加
~
:
cars %>%
group_by(speed) %>%
summarise_(d = ~mean(x))
Still does not work, but if use dist
instead of x
: 仍然不起作用,但是如果使用
dist
而不是x
:
cars %>%
group_by(speed) %>%
summarise_(d = ~mean(dist))
This works, but doesn't use x. 这有效,但不使用x。
cars %>%
group_by(speed) %>%
summarise_(d = ~mean(~x))
This also doesn't work. 这也不起作用。
I'm basically monkeying around without any idea how to make this work, or why it fails. 我基本上是四处闲逛,不知道如何进行这项工作,或者为什么会失败。
cars %>%
group_by(speed) %>%
summarise_each_(funs(mean), vars(matches(x)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.