[R] Stop R from changing matrix to numeric

Sachinthaka Abeywardana sachin.abeywardana at gmail.com
Wed Dec 17 07:55:27 CET 2014


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



More information about the R-help mailing list