rpipemagrittr

Creating an expression/call using the base R pipe


Is there a way of doing the following

ex1 <- quote(iris)
ex2 <- quote(dplyr::filter(Species == "setosa" & Sepal.Width > 4))

substitute(x %>% y, list(x = ex1, y = ex2))
#> iris %>% filter(Species == "setosa" & Sepal.Width > 4)

using the base pipe instead of the magrittr pipe?

substitute(x |> y, list(x = ex1, y = ex2))
#> Error: The pipe operator requires a function call as RHS

Solution

  • The error message is actually quite helpful here. With the base pipe you always need parentheses on the right-hand-side. So doing

    substitute(x |> y(), list(x = ex1, y = ex2))
    # (dplyr::filter(Species == "setosa" & Sepal.Width > 4))(iris)
    

    does produce a call. Then however, you will probably want to change ex2 for the call to be valid:

    ex1 <- quote(iris)
    ex2 <- quote(\(x) dplyr::filter(x, Species == "setosa" & Sepal.Width > 4))
    
    substitute(x |> y(), list(x = ex1, y = ex2)) |> eval()
    #   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    # 1          5.7         4.4          1.5         0.4  setosa
    # 2          5.2         4.1          1.5         0.1  setosa
    # 3          5.5         4.2          1.4         0.2  setosa