简体   繁体   中英

How to subset matrix with couples of row.name and col.name

I have a simple problem. I have a data frame with two columns of character variables, corresponding to row and column name "couples" from a separate matrix. I just want to use those couples to look up values in the matrix, returned in a vector.

I'm sure it is trivial, but I haven't been able to come across an answer in over an hour of googling. Here is a reproducible example:

m <- as.matrix(data.frame(a=c(1,2,3,4), 
                          b=c(14,15,16,17), 
                          c=c(27,28,29,30), 
                          d=c(43,44,45,46)))
row.names(m) <- c('w','x','y','z')

df <- data.frame(j=c('x','z','z','w','x'),
                 k=c('a','b','d','d','c'))

#I just want to "lookup" a vector of values equal to c(2,17,46,43,28)
result <- sapply(df, function(x) m[x[1],x[2]])

result
j.c k.b 
28  14

Can someone help me figure this out? sapply may not be the best approach, and I'm open to other ideas.

Just coerce the data.frame to be a matrix and use it as index

> m[as.matrix(df)]
[1]  2 17 46 43 28

Take a look at this document to realize why this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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