Search code examples
roopobjectreference-class

How to chain object$method with pipe operator %>%


I am trying to chain several methods (defined in reference class system) from the form of

Object_2 <- Object_1$first_method(para_a)

Object_3 <- Object_2$second_method(para_b) 

into, like

Object_3 <- Object_1$first_method(para_a) %>% second_method(para_b)

But this does not work and I got an error of

could not find function

I tried the operator %$%, turns out that it works for fields in an object but not for a method.

So, I'd like to ask how to do what I want in a pipeline?


Solution

  • If you want to do method chaining with reference classes, just do this:

    Object_3 <- Object_1$first_method(para_a)$second_method(para_b)
    

    The pipe operator is just another way of writing the same thing. No need to mix the two notations.

    In fact, what you've got there with the pipe is equivalent to writing the following:

    second_method(Object_1$first_method(para_a), para_b)
    

    which doesn't make any sense.