Description Author(s) Examples
vecpack is an experimental package for R, meant to help you stuff various things into a single vector (which is easy), and get them back in the right shape (which isn't). It lets you interface with optim in a more natural way: in the following example we compute a low-rank + diagonal approximation to a matrix. The most natural way of writing the cost function involves two arguments: a matrix and a scalar. Using vecpack you can send that cost function directly to optim.
Simon Barthelme
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #Packing things into a vector is easy
list(A=matrix(0,2,2),b=1:3) %>% sapply(as.vector) %>% do.call("c",.)
#Going the other way isn't: many objects correspond to the same vector
#gen.vunpack generates an "unpacking" function from an example
l <- list(A=matrix(0,2,2),b=1:3)
vunpack <- gen.vunpack(l)
vpack(l)
vpack(l) %>% vunpack
#The most common use for vpack is for interfacing with optimisation packages
#In this example we compute a rank-2 + diagonal approximation
#to the matrix X
X <- cor(USArrests )
#A cost function over two parameters: a is a scalar and B is a matrix
cfun <- function(a,B)
{
lowrank <- a*diag(4) + tcrossprod(B)
sum((lowrank-X)^2)
}
guess <- list(a=0,B=matrix(0,4,2))
#vpoptim wraps optim
res <- vpoptim(guess,cfun)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.