Get index of a specific element in vector using %>% operator

Roccer picture Roccer · Aug 11, 2017 · Viewed 9.4k times · Source

I want the index of an element in a vector x

x <- c("apple", "banana", "peach", "cherry")

With base R i would do that

which(x == "peach")

But as my x is at the end of a pipe I would like to get the index the magrittr way.

x %>% getIndex("peach")

My desired output is 3.

Answer

Axeman picture Axeman · Aug 11, 2017

You can refer the left-hand side (lhs) of the pipe using the dot (.). There's two scenarios for this:

  1. You want to use the lhs as an argument that is not in the first position. A common example is use of a data argument:

    mtcars %>% lm(mpg~cyl, data = .)
    

    In this case, margrittr will not inject the lhs into the first argument, but only in the argument marked with ..

  2. You want to include the lhs not as a single function argument, but rather as part of an expression. This is your case! In this case magrittr will still inject the lhs as the first argument as well. You can cancel that with the curly braces ({).

So you need to use . notation with { braces:

x %>% { which(. == "peach") }

[1] 3

Excluding the { would lead to trying to run the equivalent of which(x, x == "peach"), which yields an error.