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 replace the following statements below:
step1 <- mean(m)
step2 <- sum(step1)
res <- step2
Or,
res <- sum(mean(m))
With something like this :
res <- m@mean()@sum()
In some cases, that would clarify my code considerably.
EDIT1 This is a dummy example. I randomly picked 'sum' and 'mean'.
Ben has given a first piece of answer using %@% however, it prevents from using extra arguments within functions :
m %@% function1(arg1, arg2) %@% function2(arg1, arg2)
How can I work around that ?
EDIT2 Adding an example
require(xts)
require(PerformanceAnalytics)
xts.ts <- xts(rnorm(231),as.Date(13514:13744,origin="1970-01-01"))
plot(na.omit(lag( rollapply(xts.ts, width=rolling.per-1, FUN= function(x){sqrt(var(x))*sqrt(252)}), k=1)), main = "Dummy Example")
This example seems to work fine with Charles solution :
`%@%` <- function(x, f) eval.parent(as.call(append(as.list(substitute(f)), list(x), 1)))
xts.ts %@% rollapply( width = rolling.per-1, FUN= function(x) x%@%var%@%sqrt * sqrt(252) ) %@% lag( k=1) %@% na.omit %@% plot(main = "Dummy Example")
Less important to my case, but woth mentioning, the following statment fails with Charles's solution :
xts.ts %@% names <- 'ts name'