Search code examples
rdplyrmagrittr

pipe followed by .$var into function, why doesnt this work?


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

Solution

  • 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.