Here is a functional programming approach using Reduce
. It is in fact an example from ?Reduce
square <- function(x) x^2
add_5 <- function(x) x+5
x <- 1:5
## Iterative function application:
Funcall <- function(f, ...) f(...)
Reduce(Funcall, list(as.character, add_5, square,x), right = TRUE)
## [1] "6" "9" "14" "21" "30"
Or even more simply using the functional
package and Compose
This is nice as it will create the function for you
library(functional)
do_stuff <- Compose(square,add_5,as.character )
do_stuff(1:5)
## [1] "6" "9" "14" "21" "30"
I note that I would not consider either of these approaches idiomatically R
ish (if that is even a phrase)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…