Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack vector into function arguments

I have a function with four parameters, e.g.

fun <- function( x, a, b, c ) {
    sin( x * a ) * exp( -x * b ) + x * c
}

I'd like to convert that into a function with three arguments provided as a vector, fixing the first (to some df$X in this example). The following obviously works:

fx <- function( args ) {
    fun( df$X, args[ 1 ], args[ 2 ], args[ 3 ] )
}

How do I wrap this process into a function for any number of trailing function parameters, returning the function fx above? Pseudocode:

fixVector <- function( f, vec ) {
    function( args ) {
        f( vec, magic_unpack( args ) )
    }
}
fx <- fixVector( fun, df$X )

fx <- fixVector( fun, 1:10 )
fx( 1:3 )
# [1]  3.113881  6.016654  9.000350 11.999746 14.999956 17.999998 21.000001 24.000000 27.000000 30.000000

What's a suitable definition for magic_unpack()?

like image 989
mkluwe Avatar asked Aug 08 '26 03:08

mkluwe


1 Answers

I'd use do.call:

x <- 1:10
a <- 1:3

fun <- function( x, a, b, c ) {
  sin( x * a ) * exp( -x * b ) + x * c
}

fixVector <- function( f, vec, args) {
  do.call(f, c(list(vec), as.list(args)))
}

fixVector(fun, x, a)
#[1]  3.113881  6.016654  9.000350 11.999746 14.999956 17.999998 21.000001 24.000000 27.000000 30.000000
like image 89
Roland Avatar answered Aug 10 '26 17:08

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!