Using fun1 and fun2 from the question we can define both which sequentially runs them. We also test it.
both <- function(...) {
fun1(...)
fun2(...)
}
# test
both(1, 2)
## [1] 2
## [1] 3
Or if you wanted to return their outputs:
both2 <- function(...) list(fun1(...), fun2(...))
Alternately, we can define a factory function which given two functions having the same arguments creates a function which runs them in sequence.
Combine <- function(FUN1, FUN2) {
function(...) { FUN1(...); FUN2(...) }
}
# test
mewfun <- Combine(fun1, fun2)
newfun(1, 2)
## [1] 2
## [1] 3
or if you wnated to return their outputs
Combine2 <- function(FUN1, FUN2) {
function(...) list(FUN1(...), FUN2(...))
}
Answer from G. Grothendieck on Stack OverflowFor future reference you perhaps could have supplied some example data in order to showcase the problem. As i read your question, you're looking for a way to compose two functions (i.e. h(x) = g(f(x)). This can be done as follows:
myDat <- function(filename) {
dat <- readModels(filename, what = "parameters")$parameters
dat <- filter(as.data.frame(dat$unstandardized),
grepl("BY|Intercepts", paramHeader))
return(dat)
}
loading <- function(data) {
data %>%
filter(grepl("BY", paramHeader)) %>%
select(c(param, est)) %>%
separate(param, c("loading","time")) %>%
mutate(time = paste0('time',time)) %>%
spread(loading, est)
}
combined <- purrr::compose(loading, myDat)
Created on 2020-01-27 by the reprex package (v0.3.0)
We can have everything in single pipe. After extracting the 'parameters',
pull the 'unstandardized', convert to data.frame, then filter the 'paramHeader` where the values are 'BY' or 'Intercepts', and combine with the rest of the pipe from the second function
library(dplyr)
library(stringr)
library(tidyr)
loadingNew <- function(filename) {
readModels(filename, what = "parameters")$parameters %>%
pull('unstandardized') %>%
as.data.frame %>%
filter(str_detect(paramHeader, "BY|Intercepts")) %>% # not clear about two filter
filter(grepl("BY", paramHeader)) %>%
select(param, est) %>%
separate(param, c("loading","time")) %>%
mutate(time = str_c('time',time)) %>%
spread(loading, est)
# or use pivot_wider
#pivot_wider(names_from = loading, values_from = est)
}
loadingNew("cfa.out")
Do you mean this ?
fun_1 <- function(x){
x ^ 2
}
fun_2 <- function(x){
x + 1
}
fun_3 <- function(x){
fun_1(x) + fun_2(x)
}
fun_3(1)
returns 3
k <- NA
fun <- function(w){
for (i in 1:100){
k[i] <- (-i/100)^2 + exp(w)
}
sum(k)
}
fun(1)
returns 305.6632
You can use get with envir = parent.frame() and just use paste to specify the function name.
# define functions
for(i in 1:100) assign(paste0('fun',i), function(w) (-i/100)^2+exp(w) )
# sum them
sum.fun <- function(x){
out <- 0
for(i in 1:100){
fun <- get(paste0('fun',i), envir = parent.frame())
out <- out + fun(x)
}
out
}
sum.fun(2)