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
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)