I have a dataframe df:
colour shape
\'red\' circle
\'blue\' square
\'blue\' circle
\'green\' sphere
And a double matrix m with named rows/
I think I might win the shortest answer contest here as long as those are character vectors rather than factors which might be more expected unless you made specifid effort to avoid. It really only adds cbind
to convert the two df "character" vectors to a two column matrix expected by the [.matrix
function that you were very close to success in using. (And it also seems reasonably expressive.)
# Data construct
d <- data.frame(color=c('red','blue','blue','green'),
shape=c('circle','square','circle','sphere'), stringsAsFactors=FALSE)
m <- matrix(1:9, 3,3, dimnames=list(c('red','blue','green'), c('circle','square','sphere')))
# Code:
d$id <- with( d, m [ cbind(color, shape) ] )
d
color shape id
1 red circle 1
2 blue square 5
3 blue circle 2
4 green sphere 9