Reputation: 41
I am trying to transform a matrix with two columns into a matrix of another form. The thing that combines the two, is the numbering from 1:5. Does anyone have a hint on an easier way of doing the following?
Thanks in advance This is my code
data <- matrix(c(rep(1:5,6),101:130),byrow=FALSE,ncol=2)
data
[,1] [,2]
[1,] 1 101
[2,] 2 102
[3,] 3 103
[4,] 4 104
[5,] 5 105
[6,] 1 106
[7,] 2 107
[8,] 3 108
[9,] 4 109
[10,] 5 110
[11,] 1 111
[12,] 2 112
[13,] 3 113
[14,] 4 114
[15,] 5 115
[16,] 1 116
[17,] 2 117
[18,] 3 118
[19,] 4 119
[20,] 5 120
[21,] 1 121
[22,] 2 122
[23,] 3 123
[24,] 4 124
[25,] 5 125
[26,] 1 126
[27,] 2 127
[28,] 3 128
[29,] 4 129
[30,] 5 130
data.2 <- matrix(data[,2],ncol=6)
data.2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 101 106 111 116 121 126
[2,] 102 107 112 117 122 127
[3,] 103 108 113 118 123 128
[4,] 104 109 114 119 124 129
[5,] 105 110 115 120 125 130
rownames(data.2) <- c(1:5)
data.2
[,1] [,2] [,3] [,4] [,5] [,6]
1 101 106 111 116 121 126
2 102 107 112 117 122 127
3 103 108 113 118 123 128
4 104 109 114 119 124 129
5 105 110 115 120 125 130
Upvotes: 0
Views: 78
Reputation: 132626
data <- matrix(c(rep(1:5,6),101:130),byrow=FALSE,ncol=2)
res <- t(unstack(data.frame(data), X2~X1))
#clean up rownames:
rownames(res) <- gsub("X", "", rownames(res))
# [,1] [,2] [,3] [,4] [,5] [,6]
#1 101 106 111 116 121 126
#2 102 107 112 117 122 127
#3 103 108 113 118 123 128
#4 104 109 114 119 124 129
#5 105 110 115 120 125 130
Upvotes: 1
Reputation: 16080
If you are sure that first column is always 1:5 repeated n'th times then you could just simply create matrix from second column:
matrix(data[,2], nrow=5)
Or you can sort matrix by first column:
matrix(data[order(data[,1]),2], nrow=5, byrow=TRUE)
I think that @Roland idea with unstack is better than my solutions :)
Upvotes: 0