Turning a column into rows
I have , for example, this data
Rows <- c(1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,
4,开发者_Python百科4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,
9,9,9,9,9,9,9,9,9)
Columns <- c(1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9,
1,2,3,4,5,6,7,8,9)
Data <- c(1:81)
Dataset <- cbind(Rows,Columns)
Dataset <- cbind(Dataset,Data)
But these are 3 columns. That look like this:
Rows Columns Data
[1,] 1 1 1
[2,] 1 2 2
[3,] 1 3 3
[4,] 1 4 4
[5,] 1 5 5
[6,] 1 6 6
What I need is a table that looks like this:, The Row-column being the RowNrs and the Column-column being the ColumnNrs and the Data on it's respectful place
[,1][,2][,3][,4][,5][,6][,7][,8][,9]
[1,] 1 2 3 4 5 6 7 8 9
[2,] 10 11 12 13 14 15 16 17 18
[3,] 19 20 21 22 23 24 25 26 27
[4,] 28 29 30 31 32 33 34 35 36
[5,] 37 38 39 40 41 42 43 44 45
[6,] 46 47 48 49 50 51 52 53 54
[7,] 55 56 57 58 59 60 61 62 63
[8,] 64 65 66 67 68 69 70 71 72
[9,] 73 74 75 76 77 78 79 80 81
Is there any way to manipulate the "Dataset" into this table?
Is there something wrong with just:
m <- matrix(1:81, ncol = 9, nrow = 9, byrow = TRUE)
rownames(m) <- colnames(m) <- 1:9
> m
1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 10 11 12 13 14 15 16 17 18
3 19 20 21 22 23 24 25 26 27
4 28 29 30 31 32 33 34 35 36
5 37 38 39 40 41 42 43 44 45
6 46 47 48 49 50 51 52 53 54
7 55 56 57 58 59 60 61 62 63
8 64 65 66 67 68 69 70 71 72
9 73 74 75 76 77 78 79 80 81
Or if Data
is something special:
> Dataset <- cbind(Rows, Columns, 1:81)
> matrix(Dataset[,3], ncol = max(Dataset[, 2]), nrow = max(Dataset[, 1]),
+ byrow = TRUE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 2 3 4 5 6 7 8 9
[2,] 10 11 12 13 14 15 16 17 18
[3,] 19 20 21 22 23 24 25 26 27
[4,] 28 29 30 31 32 33 34 35 36
[5,] 37 38 39 40 41 42 43 44 45
[6,] 46 47 48 49 50 51 52 53 54
[7,] 55 56 57 58 59 60 61 62 63
[8,] 64 65 66 67 68 69 70 71 72
[9,] 73 74 75 76 77 78 79 80 81
maybe with
matrix(Data, nrow = 9, ncol = 9, byrow = T)
For this particular case, this should work.
Dataset <- as.data.frame(cbind(Dataset,Data))
dts <- split(Dataset, Dataset$Rows)
dts <- lapply(dts, function(x) {
t(x$Data)
})
> do.call("rbind", dts)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 2 3 4 5 6 7 8 9
[2,] 10 11 12 13 14 15 16 17 18
[3,] 19 20 21 22 23 24 25 26 27
[4,] 28 29 30 31 32 33 34 35 36
[5,] 37 38 39 40 41 42 43 44 45
[6,] 46 47 48 49 50 51 52 53 54
[7,] 55 56 57 58 59 60 61 62 63
[8,] 64 65 66 67 68 69 70 71 72
[9,] 73 74 75 76 77 78 79 80 81
I am not sure this is what you want, but from your example it seems to do the trick. You do not actually need the row and column numbers, just the data:
matrix(Data, nrow=9, ncol=9, byrow=T)
精彩评论