I have a vector x = c(1,2,3,1,2,0,1,0,0)
. I want to convert it to a matrix starting from the bottom to the top. That is, I need to fill out the entries of the matrix starting from the last entry of each column.
I tried the following:
x <- c(1,2,3,1,2,0,1,0,0)
M2 <- matrix(x, 3, 3)
M2
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 2 0
[3,] 3 0 0
However, I need it as follows:
M2
[,1] [,2] [,3]
[1,] 3 0 0
[2,] 2 2 0
[3,] 1 1 1
CodePudding user response:
We could use apply
and the rev
function:
apply(M2, 2, rev)
[,1] [,2] [,3]
[1,] 3 0 0
[2,] 2 2 0
[3,] 1 1 1
CodePudding user response:
> x=c(1,2,3,1,2,0,1,0,0)
> m=matrix(x,3,3);m[nrow(m):1,]
[,1] [,2] [,3]
[1,] 3 0 0
[2,] 2 2 0
[3,] 1 1 1
CodePudding user response:
Operating directly on x
:
y = x[seq_along(x) rep_len(c(2, 0, -2), length(x))]
matrix(y, 3)
[,1] [,2] [,3]
[1,] 3 0 0
[2,] 2 2 0
[3,] 1 1 1