user9798936
user9798936

Reputation:

How to extract a vector from a list of vectors via matrix in R

Problem:

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.

Steps of the problem:

  1. Sign numbers n vectors from 1 to n.

  2. Convert these numbers to a lower.triangular matrix M.

  3. Then, extract the vectors that match the numbers at the last row of the matrix M.

Example:

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

Answers (1)

LAP
LAP

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

Related Questions