[英]Select a column by column-name, but a different name for each row of a matrix in R?
假設我有一個矩陣,我想從column1為第一行選擇值,column5為第二行選擇值,column4為第三行(...)。 列作為列名存儲在向量中,此向量中的位置等於要在其中選擇列的行。
我怎樣才能有效地實現這一目標,即不進行循環?
(背景是:我的目的是在模擬中使用它,這就是為什么我喜歡將其矢量化以加速它)
一個最小的例子:
# 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
我只是看到循環我的方式不起作用非常有效。
我正在考慮sapply / tapply,但不知何故無法使其工作,因為有兩個參數更改(要在矩陣中搜索的行,以及要從目標columnname-vector中選擇的字母)。
我會非常感謝你的幫助。 謝謝!
賈納
PS我在這里使用“grep”,因為列名是我將運行的模擬中實際列名的子串。 但是,子串創建會使示例更復雜,因此我跳過了它。
作為幫助頁面?`[`
說,您可以使用矩陣進行子集化以獲取單個元素。 子集矩陣的每一行都是一個元素,列指定每個維度的索引。
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.