rle() is your friend in this case, i.e.,
mat1 <- apply(mat, 2, function(x) {
rl <- rle(x)
rep(rl$length, rl$lengths)
})
mat2 <- apply(mat, 2, function(x) {
rl <- rle(x)
unlist(lapply(rl$length, seq, from = 1))
})
where 'mat' is your original matrix.
I hope it helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://www.med.kuleuven.be/biostat/
http://www.student.kuleuven.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Eric yang" <yang_eric9@yahoo.com>
To: <s-news@wubios.wustl.edu>
Sent: Tuesday, March 07, 2006 12:11 PM
Subject: [S] matrix question
Dear members,
I have a simple matrix problem which is solvable using for-loops
but as they're not particular efficient I would prefer not to use
them.
Here is an example of what I'm trying to do. Suppose I have the
following matrix
>my.matrix
[,1] [,2] [,3] [,4] [,5]
[1,] 19.35602 20.82310 18.71526 17.33000 20.71457
[2,] 20.12000 21.12000 21.22000 17.33000 23.06444
[3,] 20.12000 21.12000 21.22000 17.33000 21.34383
[4,] 20.12000 21.12000 21.22000 17.33000 20.27115
[5,] 20.12000 22.12000 21.22000 18.33000 20.03679
[6,] 20.12000 22.12000 21.22000 18.33000 26.12412
[7,] 20.12000 22.12000 21.22000 19.33000 19.84222
[8,] 20.12000 23.12000 20.53322 19.33000 19.42392
[9,] 20.12000 23.12000 18.52401 19.33000 21.56694
[10,] 20.12000 23.12000 21.66532 20.37692 18.93681
[11,] 20.12000 23.80764 18.67000 21.06952 21.97545
[12,] 20.12000 21.67629 18.67000 20.33678 20.90008
[13,] 20.12000 21.00464 18.67000 19.36164 18.38411
I want to create two additional matrices (or an array) related to
this one. The first matrix counts (column by column) the number of
consecutive repeatitions of a value for each column, i.e.
>my.matrix1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 4 1
[2,] 12 3 6 4 1
[3,] 12 3 6 4 1
[4,] 12 3 6 4 1
[5,] 12 3 6 2 1
[6,] 12 3 6 2 1
[7,] 12 3 6 3 1
[8,] 12 3 1 3 1
[9,] 12 3 1 3 1
[10,] 12 3 1 1 1
[11,] 12 1 3 1 1
[12,] 12 1 3 1 1
[13,] 12 1 3 1 1
and the other matrix defines the repeatition number within the
sequence, i.e.
>my.matrix2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 1 1 1 2 1
[3,] 2 2 2 3 1
[4,] 3 3 3 4 1
[5,] 4 1 4 1 1
[6,] 5 2 5 2 1
[7,] 6 3 6 1 1
[8,] 7 1 1 2 1
[9,] 8 2 1 3 1
[10,] 9 3 1 1 1
[11,] 10 1 1 1 1
[12,] 11 1 2 1 1
[13,] 12 1 3 1 1
I would appreciate any help in constructing my.matrix1 and
my.matrix2 without the need for using for-loops.
Thanks in advance.
Regards
Eric
---------------------------------
Yahoo! Mail
Use Photomail to share photos without annoying attachments.
Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm
|