简体   繁体   English

按列名选择列,但R中矩阵的每一行都有不同的名称?

[英]Select a column by column-name, but a different name for each row of a matrix in R?

suppose I have a matrix, I want to select values from column1 for the first row, column5 for the second row, and column4 for the third row (...). 假设我有一个矩阵,我想从column1为第一行选择值,column5为第二行选择值,column4为第三行(...)。 The columns are stored as column names in a vector and the position in this vector equals the row in which the column is to be chosen. 列作为列名存储在向量中,此向量中的位置等于要在其中选择列的行。

How can I achieve this efficiently, ie without looping? 我怎样才能有效地实现这一目标,即不进行循环?

(The background is: My purpose is to use this in a simulation, that's why I would love to vectorize it to speed it up) (背景是:我的目的是在模拟中使用它,这就是为什么我喜欢将其矢量化以加速它)

A minimal example: 一个最小的例子:

    # Creating my dummy matrix
    aMatrix <-matrix(1:15,3,5,dimnames=list(NULL,LETTERS[1:5]))
    aMatrix
         A B C  D  E
    [1,] 1 4 7 10 13
    [2,] 2 5 8 11 14
    [3,] 3 6 9 12 15

    # Here are the columns I want for each row
    columns <-c("A","E","D")
    columns
    [1] "A" "E" "D"
    # means: select for row 1 column "A" = 1,
    # select for row 2 column "E" = 11,
    # select for row 3 column "D" = 12

    # Now obviously I could do looping, but this is inefficient
    for (i in columns) print(grep(i,colnames(aMatrix))) #grep is necessary for my specific matrix-names in my simulation only.
    [1] 1 #wanting col. 1 for row 1
    [1] 5 #wanting col. 5 for row 2
    [1] 4 #wanting col. 4 for row 3

I just saw that looping the way I did it does not work very efficiently. 我只是看到循环我的方式不起作用非常有效。

I was thinking about sapply/tapply but somehow could not get that to work, since there are two arguments that change (the row to be searched in the matrix, and the letter to be chosen from the target columnname-vector). 我正在考虑sapply / tapply,但不知何故无法使其工作,因为有两个参数更改(要在矩阵中搜索的行,以及要从目标columnname-vector中选择的字母)。

I would apprechiate your help a lot. 我会非常感谢你的帮助。 Thanks! 谢谢!

Jana 贾纳

PS I use "grep" here as the column names are substrings of the actual column names in the simulation I will run. PS我在这里使用“grep”,因为列名是我将运行的模拟中实际列名的子串。 But that substring-creation would have made the example more complicated, thus I skipped it. 但是,子串创建会使示例更复杂,因此我跳过了它。

As the help page ?`[` says, you can subset with a matrix to get individual elements. 作为帮助页面?`[`说,您可以使用矩阵进行子集化以获取单个元素。 Each row of the subsetting matrix is an element, and the columns specify the indices for each dimension. 子集矩阵的每一行都是一个元素,列指定每个维度的索引。

match(columns,colnames(aMatrix)) #gets the column indices
# [1] 1 5 4
b <- cbind(seq_along(columns),match(columns,colnames(aMatrix))) #subset matrix
#      [,1] [,2]
# [1,]    1    1 #first element: first row first column
# [2,]    2    5 #second element: second row fifth column
# [3,]    3    4 #third element: third row fourth column
aMatrix[b]
# [1]  1 14 12

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

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