vecpack: an R package for packing stuff into vectors

[This article was first published on R – dahtah, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

 


To leave a comment for the author, please follow the link and comment on their blog: R – dahtah.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)