Here’s a problem I’ve had again and again: let’s say you’ve defined a statistical model with several parameters. One of them is a scalar. Another is a matrix. The third one is a vector, and so on. When fitting the model the natural thing to do is to write a likelihood function that takes as many arguments as you have parameters in your model: i.e., lik(x,y,z) where x is a scalar, y a matrix and z a vector. The problem is that, while it’s the natural way of writing that function, that’s not what optimisers like “optim” want: they want a function with a single argument, and that argument should be a vector. So you have to pack everything into a vector, and write a whole lot of boilerplate code to unpack all the parameters out of that vector.

vecpack saves you from having to write all that boilerplate:

devtools::install_github("dahtah/vecpack")
library(vecpack)
#A cost function in two arguments:
cost <- function(a,b) (3*a-b+2)^2
#Call optim via vpoptim
res <- vpoptim(list(a=1,b=0),cost)
res$par

vecpack knows how to automatically pack and unpack scalars, vectors, matrices and images (from the imager package). It’s also very easy to extend.

The package is quite new, and not on CRAN yet. Feedback welcome, either here or on the issues page on github.

### Like this:

Like Loading...

*Related*

Hi

This is really useful, thank you.

Can we use optimx rather than/as well as optim?

Optimx – https://cran.r-project.org/web/packages/optimx/optimx.pdf

The take home message from a recent conference presentation I saw was that we should be using optimx rather than optim. Slides at http://wombat2016.org/slides/christoph.pdf

Thanks! Good idea, I’ll implement an interface for optimx when time permits.

Very nice, this certainly provides a useful utility.

Are you aware that your package duplicates the lift functions that have been available for some time already in the purrr package (which does a lot more, besides)?

I love purrr – it’s used internally by the package. The lift functions don’t cover this specific case (yet, as far as I know), that’s why I wrote this package.

Are you aware of the “relist” function, in the standard “utils” package? (Just type help(relist).)

Thanks Radford! No, I didn’t know about relist, looks like I’ve been re-inventing part of the wheel. relist relies on attributes, though, which can get lost along the way. vecpack has a different system.