Dear all,
Here's an example of what I would like to do without
using a for-loop.
I have the following data
my.data <- matrix(c(sample(20, size=10, F), sample(4,
size=10, T), rnorm(10, 5, 1), rnorm(10, 20, 4),
rnorm(10, 10, 2), rnorm(10, 10,3)),
ncol=6)
> my.data
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 6 2 3.858922 29.48057 8.027945 14.362423
[2,] 5 1 4.885107 22.78082 8.182446 3.066463
[3,] 11 3 5.732712 12.55876 11.152502 12.060518
[4,] 16 4 4.226750 15.90435 8.963558 13.354798
[5,] 10 1 5.110561 15.68133 7.045130 9.726243
[6,] 7 3 4.554621 15.95656 10.694539 6.580981
[7,] 9 2 4.508211 23.41050 9.322254 9.989812
[8,] 3 4 5.977006 22.99636 10.081296 12.683619
[9,] 4 4 4.127606 20.87818 9.620855 11.915763
[10,] 13 2 6.308710 15.11741 7.739558 6.820841
I would like to populate a bigger matrix with this
information such that the 1st column refers to the row
of the new matrix and the 2nd column refers to the
column sequence. The data is contained in columns 3 to
6. If column 2 contains a 1 then the data is put into
columns 1, 5, 9, 13 of the new matrix, if column 2
contains a 2 then the data is put into columns 2, 6,
10, 14 of the new matrix - similarly for 3 and 4 in
column 2.
The for-loop is as follows:
new.matrix <- matrix(0, 20, 16)
for(i in 1:4) {
data <- which(my.data[,2]==i)
row <- my.data[data, 1]
col <- seq(i, by=4, length=4)
new.matrix[row, col] <- my.data[data, 3:6]
}
Can this be done without the need for a for-loop?
Thanks in advance for any help.
Regards,
Eric
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
|