0

Variants of this question have been asked a lot, I also read about 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"

Of course this does not work:

cars %>%
  group_by(speed) %>%
  summarise(d = mean(x))

So I use SE version of summarise:

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:

cars %>%
  group_by(speed) %>%
  summarise_(d = ~mean(dist))

This works, but doesn't use 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.

juwi
  • 98
  • 7

1 Answers1

2
cars %>%
    group_by(speed) %>%
    summarise_each_(funs(mean), vars(matches(x)))
Adam Quek
  • 6,973
  • 1
  • 17
  • 23
  • Thank you! My problem is, was doing something more like this `cars %>% group_by(speed) %>% summarise_(d = ~quantile(dist, c(0.95), na.rm =T)[1])` Do you also have a solution for that? – juwi May 25 '17 at 10:13
  • 1
    I tend to define a function with the argument first, e.g. `quantiles <- function(x) quantile(x, .95, na.rm=T)`. This way, the `summarise_each` can still run accordingly: `cars %>% group_by(speed) %>% summarise_each_(funs(quantiles), vars(matches("dist")))` – Adam Quek May 25 '17 at 11:37