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

后端 未结 6 1929
旧时难觅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 20:59

    Another answer Using the reshape2 and plyr (optional just for join) packages.

    require(plyr)
    require(reshape2)
    
    Df <- data.frame(colour = c("red", "blue", "blue", "green"), 
                      shape = c("circle", "square", "circle", "sphere"))
    
    Mat <- matrix(1:9, dimnames = list(c("red", "blue", "green"),
                                       c("circle", "square", "sphere")), 
                        nrow = 3)
    
    Df2 <- melt.array(Mat, varnames = c("colour", "shape"))
    
    join(Df, Df2)
    result <- join(Df, Df2)
    
    join(Df, Df2)
    Joining by: colour, shape
      colour  shape value
    1    red circle     1
    2   blue square     5
    3   blue circle     2
    4  green sphere     9
    

    Hope this help

提交回复
热议问题