hxd1011 hxd1011 - 1 year ago 88
R Question

Better libraries in R for matrix operation

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.

e=A %*% x - b
v=t(e) %*% e


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

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

  • my function
    has some matrix operations, but it returns a scalar,
    also does not like that (it treats it as a matrix class), so I need to do

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

Answer Source

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 ...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download