R Pipelining functions

前端 未结 5 1997
北荒
北荒 2020-12-10 12:14

Is there a way to write pipelined functions in R where the result of one function passes immediately into the next? I\'m coming from F# and really appreciated this ability b

5条回答
  •  情深已故
    2020-12-10 12:49

    Since this question was asked, the magrittr pipe has become enormously popular in R. So your example would be:

    library (magrittr)
    
    fx <- function (x) {
         x %>%
         `^` (2) %>%
         `+` (5)  %>%
         as.character ()
         }
    

    Note that the backquote notation is because I'm literally using R's built-in functions and I need to specially quote them to use them in this manner. More normally-named functions (like exp or if I'd created a helper function add) wouldn't need backquotes and would appear more like your example.

    Note also that %>% passes the incoming value as the first argument to the next function automatically, though you can change this. Note also that an R function returns the last value calculated so I don't need to return or assign the calculation in order to return it.

    This is a lot like the nice special operators defined by other answers, but it uses a particular function that's widely used in R now.

提交回复
热议问题