TransWikia.com

How to use pipe operator in Mathematica?

Mathematica Asked by kittygirl on November 27, 2020

t = Table[i1 + i2 i3, {i1, 2}, {i2, 3}, {i3, 2}]
ArrayDepth[t]

How to use "pipe operator" in Mathematica Version 11.0?

In R, with library
magrittr
I can use a pipeline specification as below:

Table[i1 + i2 i3, {i1, 2}, {i2, 3}, {i3, 2}] %>% ArrayDepth[.]

How to use "pipeline specifications" in Mathematica?

3 Answers

Perhaps you're looking for

Table[i1 + i2 i3, {i1, 2}, {i2, 3}, {i3, 2}] // ArrayDepth
(*3*)

Correct answer by Ulrich Neumann on November 27, 2020

In order to utilize the post fix operator // in WL in the way the R library magrittr implements/uses %>% several things have to be kept in mind.

  • R's magrittr operator %>% :

    1. Assumes that the pipeline value is the first and only argument by default

      • Many of the tidyverse package functions rely heavily on this
    2. If a function needs only the first argument to be specified only the function name can be used

    3. Different argument location of the pipeline value can be specified with .

  • In WL using the operator // :

    1. Often translating R tidyverse pipeline workflows in WL pipelines with // requires the argument location specification of the pipeline object

    2. If a function needs only one argument to be specified only the function name can be used

    3. The argument slot specification #1 should be used (instead of . of R's magrittr.)

Clarification examples follow.

Example 1

R-magrittr:

 iris %>% nrow %>% runif

WL:

ExampleData[{"Statistics", "FisherIris"}] // Length // RandomReal[1, #1] &

Example 2

R-magrittr:

 iris %>% nrow %>% runif( n = 3, min = -10, max = .) 

WL:

ExampleData[{"Statistics", "FisherIris"}] // Length //  RandomReal[{-10, #1}, 3] &

Answered by Anton Antonov on November 27, 2020

Note that in addition to the postfix notation //, you can also set up a pipeline of operators with RightComposition (/*) that can be re-used later. For example:

pipeline = Map[f] /* Apply[g] /* h
Range[5] // pipeline
Range[10] // pipeline

(* this also works, though it's maybe less intuitive *)
pipeline @ Range[5]

You can also use Composition (@*) if you prefer to read the other way around (i.e., the functions closest to the argument get applied first):

pipeline2 = h @* Apply[g] @* Map[f]
pipeline2 @ Range[5]

Answered by Sjoerd Smit on November 27, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP