Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

magrittr

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.

like image 919
Roccer Avatar asked Mar 08 '23 08:03

Roccer


2 Answers

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.

like image 146
Axeman Avatar answered Mar 17 '23 16:03

Axeman


Or simply:

x %>% match(x = "peach")

# [1] 3

(Differs from which() in that it only gives you the first match):

y <- c("apple", "banana", "peach", "cherry", "peach")
y %>% `==`("peach") %>% which()
# [1] 3 5
y %>% match(x = "peach")
# [1] 3
like image 22
Aurèle Avatar answered Mar 17 '23 17:03

Aurèle