[R] Using as.polynomial() over a matrix
Raznahan, Armin (NIH/NIMH) [E]
raznahana at mail.nih.gov
Tue Oct 5 03:10:06 CEST 2010
Hello All
First - a warning. I'm not very R or programming savvy.
I am trying to do something without much luck, and have scoured help-pages, but nothing has come up. Here it is:
I have a matrix (m) of approx 40,000 rows and 3 columns, filled with numbers.
I would like to convert the contents of this matrix into another matrix (m_p), where the numbers of (m) have been coerced into a polynomial - using a function called "as.polynomial()" from the package (polynom). Each row of (m) contains 3 terms to be made into a polynomial in the equivalent row of (m_p).
I have tried a coupe of things:
------------------------------
1. Using apply()
m_p<-apply(m, 2, as.polynomial)
Here is what happens..
> dim(m)
[1] 40962 3
> m_p<-apply(m, 2, as.polynomial)
> m_p[1:5,]
dM_I dM_a.c dM_a.c.sq
[1,] -0.00593058 -0.000688 3.65e-05
[2,] -0.01913294 0.000103 1.41e-04
[3,] -0.01317958 -0.001190 1.49e-04
[4,] -0.02651112 -0.001550 2.37e-04
[5,] -0.01680289 -0.003520 2.86e-04
So - looks like the coercion hasn't worked. BUT, if I do things piecemeal - it looks ok..
> m_p1<-as.polynomial(m[1,])
> m_p1
-0.00593058 - 0.000688*x + 3.65e-05*x^2
--------------------------------
-------------------------------
2. This made me think I was making some wrong assumptions using apply(). So I wrote a function "test()", to take each row of (m) , use as.polynomial() on it, and stick the results into a new matrix, which it would then return..
test<-function(x){
a<-nrow(x)
b<-ncol(x)
c<-matrix(0, a, b)
for (i in 1:a) {
c[i,]<-as.polynomial(x[i,]) }
return (c)
}
> m_p<-test(m)
> dim(m_p)
[1] 40962 3
> m_p[1:5,]
[,1] [,2] [,3]
[1,] -0.00593058 -0.000688 3.65e-05
[2,] -0.01913294 0.000103 1.41e-04
[3,] -0.01317958 -0.001190 1.49e-04
[4,] -0.02651112 -0.001550 2.37e-04
[5,] -0.01680289 -0.003520 2.86e-04
-------------------
I don't know why I can do what I want when taking each line at a time, but not when trying to run through the whole matrix.
Sorry if missing something obvious. Any help/pointers would be very gratefully received
Thanks v much
Armin
More information about the R-help
mailing list