Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give common missing argument in functional

I have a bunch of little functions that generate random strings similar to rnorm or sample. These functions all have common arguments, for the sake of simplicity let's say one common argument is n. I'd like to make a larger function (functional) that takes the n as and argument plus ... that can be any of the little functions. This meta function evaluates the little functions with the setn if they have this argument. here's an example:

## LITTLE FUNCTIONS

fun1 <- function(n, x = 1:10) sample(x, n, TRUE)
fun2 <- function(n, x = LETTERS) sample(x, n, TRUE)
fun3 <- function(n, x = 50) rnorm(n, x)
fun4 <- function(n, x = 100, y = 10) rnorm(n, x, y)

FUNCTIONAL (META FUNCTION)

combiner <- function(n, ...){

## Where the magic needs to happen.  Set n for `fun1` `fun2` and `fun4`
## evaluate all these functions

}

## Here we pass `n = 6`
combiner(
    6,
    fun1(),
    fun2,
    rnorm(),
    fun4(y=8)
)

I'd like it to evaluate functions even if they're missing () as Is the case with fun2 above but this is more of a nicety. I think this is possible because the magrittr pipes can do this.

## DESIRED OUTPUT

list(
    fun1(6),
    fun2(6),
    rnorm(6),
    fun4(6, y=8)
)


## OUTPUT IS SEED DEPENDANT
## [[1]]
## [1] 2 1 6 6 1 1
## 
## [[2]]
## [1] "V" "Z" "A" "F" "F" "G"
## 
## [[3]]
## [1] -0.91932716 -0.05833169  1.75440750  2.19959565 -0.11145315  1.32216601
## 
## [[4]]
## [1] 107.48747  89.55798  93.15771 111.32380 100.82104 104.07829
like image 283
Tyler Rinker Avatar asked Apr 14 '15 01:04

Tyler Rinker


People also ask

What is missing argument to function call?

The missing argument is an object that triggers an error if and only if it is the result of evaluating a symbol. No error is produced when a function call evaluates to the missing argument object.

What function does not take any arguments?

1 Answer. Best explanation: The functions fillcolor(), goto() and setheading() accept arguments, whereas the function position() does not accept any arguments.


1 Answers

Here's how I'd approach this:

combiner <- function(n, ...) {
    ## Capture the unevaluated calls and symbols passed via ...
    ll <- as.list(substitute(list(...)))[-1]
    ## Process each one in turn
    lapply(ll, FUN = function(X) {
        ## Turn any symbols/names into calls
        if(is.name(X)) X <- as.call(list(X))
        ## Add/replace an argument named n
        X$n <- n
        ## Evaluate the fixed up call
        eval(X)
    })
}

combiner(6, fun1(), fun2, rnorm(), fun4(y=8))
# [[1]]
# [1] 3 8 9 7 4 7
# 
# [[2]]
# [1] "Z" "M" "U" "A" "Z" "U"
# 
# [[3]]
# [1]  0.6100340 -1.0323017 -0.6895327  1.2534378 -0.3513120  0.3116020
#  
# [[4]]
# [1] 112.31979  91.96595  79.11932 108.30020 107.16828  89.46137
like image 85
Josh O'Brien Avatar answered Sep 28 '22 04:09

Josh O'Brien