Populate a new column in a dataframe with a lookup from a double matrix

后端 未结 6 1932
旧时难觅i
旧时难觅i 2021-02-15 20:27

I have a dataframe df:

colour  shape
\'red\'   circle
\'blue\'  square
\'blue\'  circle
\'green\' sphere

And a double matrix m with named rows/

6条回答
  •  爱一瞬间的悲伤
    2021-02-15 21:23

    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
    

提交回复
热议问题