Select a column by column-name but a different name for each row of the matrix in R?

Suppose I have a matrix, I want to select values ​​from column 1 for the first row, column5 for the second row, and column4 for the third row (...). Columns are stored as column names in a vector, and the position in that vector is equal to the row where the column should be selected.

How can I achieve this efficiently i.e. without a loop?

(Background: my goal is to use this in a simulation, so I would like to vectorize it to speed it up)

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 the loop I was doing was not working very efficiently.

I was thinking about sapply / tapply, but somehow I couldn't get it to work as two arguments change (the string to look for in the matrix and the letter to be selected from the target vector-name).

I would advise you a lot. Thank!

Yana

PS I am using "grep" here as the column names are substrings of the actual column names in the simulations I will be running. But this substring creation would have made the example more complicated, so I skipped it.

+3


source to share


1 answer


As the man page says ?`[`

, you can subset with a matrix to get individual items. Each row of the subset matrix is ​​an element, and the columns define 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

      

+5


source







All Articles