# [R] Stop R from changing matrix to numeric

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Wed Dec 17 15:05:08 CET 2014

```as.matrix(c(1,1)) gives a matrix with only one column, but your function assumes you have at least two columns (you refer to x[,2]). Please make your examples reproducible (run it yourself in a fresh instance of R) to obtain best results with questions on this list.

However, you might just be needing to read about the drop parameter for indexing:

?"["

which is also mentioned in the Introduction to R document that accompanies the software in the section on indexing.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
---------------------------------------------------------------------------
Sent from my phone. Please excuse my brevity.

On December 16, 2014 10:55:27 PM PST, Sachinthaka Abeywardana <sachin.abeywardana at gmail.com> wrote:
>I have the following cost function:
>cost<-function(x){
>    x[,1]*sin(4*x[,1])+1.1*x[,2]*sin(2*x[,2])
>}
>
>If I send in a matrix which has MORE than one row and 2 columns, this
>works fine. However, if I try to do cost(t(as.matrix(c(1,1)))) it
>gives me an index error. When I tried debugging it, I found that the
>type of matrix 'x' was converted to numeric.
>
>How do I prevent this conversion from matrix to numeric if its a
>matrix with just one row? The only way it would work is if I have:
>x[1]*sin(4*x[1])+1.1*x[2]*sin(2*x[2]), which in turn wont work with a
>matrix input.
>
>Thanks,
>Sachin
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help