0

Can someone tell me why example 1 is not working but example 2 works? (I pipe a data set into mean function, but want only one variable, but if I do the selection first and pipe the result there is no problem)

iris %>% mean(.$Sepal.Length)

NA
Warning message:
In mean.default(., .$Sepal.Length) :
argument is not numeric or logical: returning NA

iris %>% .$Sepal.Length %>% mean()

 5.843333
989
  • 12,579
  • 5
  • 31
  • 53
Roel Hogervorst
  • 299
  • 3
  • 13
  • You can use `summarise` to apply functions i.e. `iris %>% summarise(val=mean(Sepal.Length)) %>% .$val` – akrun Jun 18 '16 at 08:49
  • thanks @akrun, but I was not actually looking for a way to apply the mean function to my data frame, the second part does, but wondering why version 1 doesn't work while version 2 does – Roel Hogervorst Jun 18 '16 at 08:53
  • I guess it is evaluating the mean before the `.$Sepal.Length` and `mean` will work on a `vector` or `matrix`. You can also check `iris %>% mean()` – akrun Jun 18 '16 at 08:55
  • 1
    That's a interesting idea @akrun! Indeed the error message with `iris %>% mean( )` looks the same. So the order of evaluation is mean first and then the dot? – Roel Hogervorst Jun 18 '16 at 09:00
  • Another approach is `iris %>% with(., mean(Sepal.Length))` – akrun Jun 18 '16 at 09:11
  • 1
    @akrun i bet there's no need for `.,` in the `with` but no R to test. – Tyler Rinker Jun 18 '16 at 22:23

1 Answers1

3

If you unpipe your code

iris %>% mean(.$Sepal.Length)

becomes

mean(iris, iris$Sepal.Length)

Essentially, you're trying to apply mean to a data.frame and there's no method for doing that.

The unpiped equivalent of

iris %>% .$Sepal.Length %>% mean()

is

mean(iris$Sepal.Length)

And there is a method of mean for numeric vectors.

Remember that in a pipe, the entire object on the left hand side of the pipe is passed to the first argument on the right hand side (unless otherwise represented by arg = .). Trying to pass only part of the object tends not to work so well.

Benjamin
  • 16,897
  • 6
  • 45
  • 65
  • 1
    right, and in magrittr-style piping it would probably be `iris %$% Sepal.Length %>% mean` – talat Jun 18 '16 at 08:59
  • Oh how I love `magrittr`. I need to learn to use `%$%` more often. (I'm guilty of having used `iris %>% `$(Sepal.Length)` %>% mean`, which just looks so wrong. – Benjamin Jun 18 '16 at 09:02
  • Thanks @Benjamin ! It is a bit weird that `%>% .$var` is represented as `df, df$var`. – Roel Hogervorst Jun 18 '16 at 09:13
  • I often fall back on magrittr, @docendodiscimus, for these kind of operations, but it sort of breaks the flow in a chain of commands: `df %>% filter(df) %>% select(df) %$% mean(var)` – Roel Hogervorst Jun 18 '16 at 09:16