简体   繁体   English

如何通过R中的矩阵从向量列表中提取向量

[英]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 . 我想对从1n向量进行数字签名。 Then, I would like to convert these number to a lower.triangular matrix. 然后,我想将这些数字转换为下lower.triangular矩阵。 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 . 符号编号从1n n向量。

  2. Convert these numbers to a lower.triangular matrix M. 将这些数字转换为下lower.triangular矩阵M。

  3. Then, extract the vectors that match the numbers at the last row of the matrix M. 然后,提取与矩阵M最后一行中的数字匹配的向量。

Example: 例:

Assume that I have a list of 10 vectors ( X ): 假设我有10向量( 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. 然后,我想将它们从110进行排序,其中1表示第一个向量,依此类推。 Then, I will have a vector of these numbers, say x = c(1:10) . 然后,我将得到这些数字的向量,例如x = c(1:10) Then, I would like to convert it to a lower triangular matrix M . 然后,我想将其转换为下三角矩阵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 . 现在所需的向量(要从整个向量中提取)是x4, x7, x9, and x10和10。换句话说,我需要提取x4, x7, x9, and x10

Hence, I would like to extract the vectors match these number. 因此,我想提取与这些数字匹配的向量。

Any idea or help, please? 有什么想法或帮助吗?

You could use paste : 您可以使用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. paste0("x", newX[newX != 0]将创建字符向量"x4", "x7", "x9", "x10" ,可用于为列表建立索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM