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.
You can refer to the left-hand side (lhs) of the pipe using the dot (.
). There's two scenarios for this:
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 .
.
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.