[R] Inserting a new row in a matrix
culpritNr1
ig2ar-saf1 at yahoo.co.uk
Tue Oct 21 22:16:11 CEST 2008
Hi Alwx99,
Nobody has answered your email, so, I am left with the honour of
disappointing you.
In R, matrices are not dynamically allocated. If you are a C/C++/Fortran/etc
programmer you know what I am talking about.
Lets assume that you are not such programmer. Inserting a row would tell R
to push a little the memory that holds your matrix so that a now row can be
squeezed in. R does not do that, unfortunately. You have to come up with
your own workarounds.
I suggest that you consider rebuilding your matrix each "for" loop cycle
with an infamous rbind. Something like
for (...blah...) {
...blah...
MatrixWithOneMoreRow <- rbind(PartialMatrixAboveRow, NewRow,
PartialMatrixBelowRow)
}
Sorry. I recently discovered that R is not as modern as me and you expected.
No dynamical matrices. More on this?: search this List with "in-place
appending to a matrix".
PLEASE, somebody, prove me wrong!
Your culpritNr1
Alex99 wrote:
>
> Hi guys,
>
> I need to insert a row to a matrix in a for loop. I have matrix named
> "Avg" which is a 5x4 matrix of zeros.
> I have a file named "A"(4 rows,14 columns) which I make a sample of it 5
> times. each time I get the mean for each column and put the result in the
> "Avg" matrix. this is my code:
>
> Avg=matrix(0,5,4)
>>
>> for(i in 1:5){
> + res=(A[sample(nrow(A), 5),])
> + insertRow(Avg,i,colMeans(res))
> + show(res)
> + show(Avg)
> + }
>
> this is my result(I just copied the first sample) :
>
> s1 s2 s3 s4
> 2 1 0 1 0
> 3 0 0 0 0
> 11 0 0 0 0
> 5 0 1 0 1
> 12 0 0 0 0
> [,1] [,2] [,3] [,4]
> [1,] 0 0 0 0
> [2,] 0 0 0 0
> [3,] 0 0 0 0
> [4,] 0 0 0 0
> [5,] 0 0 0 0
>
> it's suppose to put .2 .2 .2 .2 in the first row of the matrix but as you
> see it's all 0. any idea why and how to fix it?
>
> Thanks,
>
>
--
View this message in context: http://www.nabble.com/Inserting-a-new-row-in-a-matrix-tp20096320p20098332.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list