[R] Stop R from changing matrix to numeric
Peter Alspach
Peter.Alspach at plantandfood.co.nz
Wed Dec 17 19:59:34 CET 2014
Tena koe Sachin
The following might help you understand what is going on and how to rectify it.
cost <- function(x) {x[,1]*x[,2]}
ttMat <- matrix(1:4, ncol=2)
ttMat
cost(ttMat)
cost(ttMat[1,])
cost(as.matrix(ttMat[1,]))
cost(t(as.matrix(ttMat[1,])))
cost(matrix(ttMat[1,], ncol=2))
str(ttMat)
str(ttMat[1,])
str(as.matrix(ttMat[1,]))
str(t(as.matrix(ttMat[1,])))
str(matrix(ttMat[1,], ncol=2))
HTH .....
Peter Alspach
-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Sachinthaka Abeywardana
Sent: Wednesday, 17 December 2014 7:55 p.m.
To: r-help at r-project.org
Subject: [R] Stop R from changing matrix to numeric
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
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
The contents of this e-mail are confidential and may be ...{{dropped:14}}
More information about the R-help
mailing list