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

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

    #recreating your data
    dat <- read.table(text="colour  shape
    'red'   circle
    'blue'  square
    'blue'  circle
    'green' sphere", header=TRUE)
    
    d2 <- matrix(c(1:9), ncol=3, nrow=3, byrow=TRUE)
    dimnames(d2) <-list(c('circle', 'square', 'sphere'),
    c("red", "blue", "green"))
    d2<-as.table(d2)
    
    #make a list of matching to the row and column names of the look up matrix
    LIST <- list(match(dat[, 2], rownames(d2)), match(dat[, 1], colnames(d2)))
    #use sapply to index the lookup matrix using the row and col values from LIST 
    id <- sapply(seq_along(LIST[[1]]), function(i) d2[LIST[[1]][i], LIST[[2]][i]])
    #put it all back together
    data.frame(id=id, dat)
    

提交回复
热议问题