Search code examples
rmagrittr

The interchangeability of "%>%" and "|>" in R when conducting t-test


This is the dataframe I created using Iris dataset.

library(datasets)
df = iris[which(iris$Species == "setosa" | iris$Species == "versicolor"),] 
# Success
df %>% t.test(Sepal.Length ~ Species, data = .)
# Error is.atomic(x) is not TRUE
df |> t.test(Sepal.Length ~ Species, data = .)

I wonder why they did not work the same and when will %>% and |> be uninterchangeable?


Solution

  • In the second approach, you use ., which is the magrittr placeholder when you should use _ (which is the native pipe's placeholder).

    This does work:

    df |> t.test(Sepal.Length ~ Species, data = _)
     
    # Welch Two Sample t-test
    # 
    # data:  Sepal.Length by Species
    # t = -10.521, df = 86.538, p-value < 2.2e-16
    # alternative hypothesis: true difference in means between group setosa and group versicolor is not equal to 0
    # 95 percent confidence interval:
    #   -1.1057074 -0.7542926
    # sample estimates:
    #   mean in group setosa mean in group versicolor 
    # 5.006                    5.936 
    

    You can find out much more about the differences beyond the scope of this question here: What are the differences between R's new native pipe `|>` and the magrittr pipe `%>%`?