Reputation: 3
Given a series of functions B1, B2, .., B20
How can you create a function that calls all or some of these predefined functions simultaneously?
What I want for example is a function(start=B1,end=B12)
that will call B1 TO B12
functions at the same time.
Upvotes: 0
Views: 459
Reputation: 94182
You can construct any R object name as a string and then get
it.
> B1 = function(x){x^1}
> B2 = function(x){x^2}
> B3 = function(x){x^3}
> B4 = function(x){x^4}
> getBN = function(N){get(paste0("B",N))}
> getBN(1)
function(x){x^1}
> getBN(2)(2)
[1] 4
If you really want to do this I'd define your function like this:
doBs = function(start=1, end=12, prefix="B"){..stuff happens..}
and that function would be a loop over start:end
, construct the function name, evaluate it.
If you really want to call it like doBs(start=B1, end=B2)
then you need to get the names of the things passed which you can do with deparse
and substitute
:
doBs = function(start=B1){first = deparse(substitute(start));first}
> doBs()
[1] "B1"
> doBs(B2)
[1] "B2"
>
and then splitting the string and working out the start/end values to construct all the function names as string from B{start} to B{end} and then get
ting them and calling them.
Or do the right thing and stick the functions in a list.
Upvotes: 1
Reputation: 15395
I would recommend putting all your functions in a list:
B <- list(B1, B2, ..., B20)
That way you can call them with another function:
callB <- function(callnum, ...){
for(i in callnum){
B[[i]](...)
}
}
Upvotes: 1