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

后端 未结 6 1928
旧时难觅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:10

    You could also convert the matrix m to a vector and then match the ID to the colour and shape values:

    df<-data.frame(colour=c("red","blue","blue","green"),
      shape=c("circle","square","circle","sphere"))
    
    
    m<-matrix(1:9,nrow=3,dimnames=list(c("red","blue","green"),
      c("circle","square","sphere")))
    
    
    mVec<-as.vector(m)
    

    The next step matches the colour in df to the appropriate dimname in the m matrix, then adds an integer corresponding to the shape. The result in the index of the m vector with the corresponding ID.

    df$ID<-mVec[match(df$colour, dimnames(m)[[1]]) + (dim(m)[1]*
      (match(df$shape, dimnames(m)[[2]]) - 1))]
    

提交回复
热议问题