Reputation:
I have a number of vectors. I would like to sign numbers to these vectors starting from 1
to n
. Then, I would like to convert these number to a lower.triangular
matrix. After that, I would like to extract the vectors comes at the last row of the matrix.
Sign numbers n
vectors from 1
to n
.
Convert these numbers to a lower.triangular
matrix M.
Then, extract the vectors that match the numbers at the last row of the matrix M.
Assume that I have a list of 10
vectors (X
):
X <- list(x1=c(1:3), x2=(2:5), x3=c(4:2), x4=c(5:7), x5=c(12,34,54), x6=c(3:6), x7=c(3:6), x8=c(3,4,5), x9=c(44,56,7), x10=c(34,5,4))
Then, I would like to order them from 1
to 10
, where 1
refers to the first vector, and so on. Then, I will have a vector of these numbers, say x = c(1:10)
. Then, I would like to convert it to a lower triangular matrix M
.
M <- matrix(0,5,5)
> M[lower.tri(M, diag=FALSE)] <- x
> M
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
[2,] 1 0 0 0 0
[3,] 2 5 0 0 0
[4,] 3 6 8 0 0
[5,] 4 7 9 10 0
Now, I would like to extract, the last row.
> tail(M, 1)
[,1] [,2] [,3] [,4] [,5]
[5,] 4 7 9 10 0
> newX <- as.vector(tail(M,1))
> newX
[1] 4 7 9 10 0
Now the wanted vectors (to be extracted from the whole vectors) are 4, 7, 9, and 10. In other words, I need to extract, x4, x7, x9, and x10
.
Hence, I would like to extract the vectors match these number.
Any idea or help, please?
Upvotes: 1
Views: 232
Reputation: 6685
You could use paste
:
X[paste0("x", newX[newX != 0])]
$`x4`
[1] 5 6 7
$x7
[1] 3 4 5 6
$x9
[1] 44 56 7
$x10
[1] 34 5 4
paste0("x", newX[newX != 0]
will create the character vector "x4", "x7", "x9", "x10"
which you can use for indexing the list.
Upvotes: 1