Method chaining with R

前端 未结 4 1426
一生所求
一生所求 2021-02-20 14:19

Is it possible to chain functions in R?

Sample data:

m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)

For example, I would like to r

4条回答
  •  孤独总比滥情好
    2021-02-20 15:03

    Try the functional package:

    library(functional)
    squared <- function(x)x*x
    Compose(sum, squared)(m)
    ## [1] 44100
    squared(sum(m))
    ## [1] 44100
    

    EDIT:

    Regarding the question in the comments of another response about arguments here is an example of composing with arguments. Curry is also from the functional package:

    addn <- function(n, x) x + n
    Compose(Curry(addn, 1), squared)(10)
    ## [1] 121
    squared(addn(1, 10))
    ## [1] 121
    

    EDIT 2:

    Regarding question about debugging, debug works if the function is curried. If its not already curried then wrap it in Curry :

    # this works since addn is curried
    debug(addn)
    Compose(Curry(addn, 1), squared)(10)
    
    # to debug squared put it in a Curry -- so this works:
    debug(squared)
    Compose(Curry(addn, 1), Curry(squared))(10)
    

提交回复
热议问题