I wanted to write a function that is the composition of two functions using the pipe operator %>%
, so that, for instance, the following are equivalent (imagine I call it %O%
):
iris[1:4] %>% lapply(FUN = function(x) hist(sample(x))
iris[1:4] %>% lapply(FUN = sample %O% hist)
I want it in this direction (not hist %O% sample
) because it would follow the same logic as %>%
.
I've come to something like that:
'%O%' <- function(lhs1, rhs1){
return(
function(x){
return(x %>% lhs1 %>% rhs1)
})
}
However, it raises errors when I try
iris[1:4] %>% lapply(FUN = sample(size = 100, replace = TRUE) %O% hist)
What should I do to allow the parameters to be understood by %>%
inside the %O%
function? Is it an eval
and quote
problem? I also don't really understand how %>%
is able to read arguments in lhs
and rhs
.
Any help will be appreciated. Thanks a lot!
Use a magrittr
functional sequence instead?
f <- . %>% sample() %>% hist()
iris[1:4] %>% lapply(f)
Or just
iris[1:4] %>% lapply(. %>% sample() %>% hist())