hxd1011 - 2 months ago 6x

R Question

This question is related to a question I asked before

Matrix and vector multiplication operation in R

Specifically, I feel painful to do some matrix operations in R. For example, for the following code, there are couple of additional steps for me to make it run.

`f<-function(x,A,b){`

e=A %*% x - b

v=t(e) %*% e

return(as.numeric(v))

}

A=matrix(runif(300),ncol=3)

b=matrix(runif(100),ncol=1)

x0=runif(3)

optimx::optimx(x0,f,A=A,b=b, method="BFGS")

- only accepts a vector as initial value, so I cannot write x0 as a column vector like the assignment for
`optimx`

and`A`

.`b`

- my function has some matrix operations, but it returns a scalar,
`f`

also does not like that (it treats it as a matrix class), so I need to do`optimx`

.`as.numeric()`

Is there a better way to enable me to do matrix operations in

`R`

Answer

I'm not optimistic that you're going to find you what you want, and trying to work around the idiom of a language - rather than sucking it up/adapting to it - is often a recipe for continuing pain. A few thoughts:

`c(v)`

and`drop(v)`

have the same effect`as.numeric(v)`

;`c(v)`

is terser and`drop(v)`

is (perhaps) semantically clearer`optim()`

(unlike`optimx::optimx`

) doesn't complain about being handed a column vector (in R terms, a 1-column matrix), and works the same as in your example`crossprod(e)`

is equivalent to (and faster than)`t(e) %*% e`

You *could* use MATLAB (you haven't told us why you're using R), or (if you can't afford it) try Octave ...

Source (Stackoverflow)

Comments