Home > database >  R replace element with the element that has the corresponding row number in another matrix
R replace element with the element that has the corresponding row number in another matrix

Time:08-01

Given the following df and df2, I would like to create a 3x3 matrix where each element is the explore_ind in df2 with the hex that corresponds to the value given in df.

df<-rbind(c(1,4,NA),c(2,1,4),c(1,NA,NA))

     [,1] [,2] [,3]
[1,]    1    4   NA
[2,]    2    1    4
[3,]    1   NA   NA

df2<-structure(list(hex = c(1, 2, 3, 4), explore_ind = c("A","B", "C", "D")), class = "data.frame", row.names = c(NA, -4L))

  hex explore_ind
1   1           A
2   2           B
3   3           C
4   4           D

The result should be:

     [,1] [,2] [,3]
[1,]    A    D   NA
[2,]    B    A    D
[3,]    A   NA   NA

CodePudding user response:

We could just use the index in 'df' to get the corresponding elements from 'explore_ind' (as they index starts from 1) and then assign back to the original data 'df'

df[] <-  df2$explore_ind[df]

-output

> df
     [,1] [,2] [,3]
[1,] "A"  "D"  NA  
[2,] "B"  "A"  "D" 
[3,] "A"  NA   NA  

A more general approach i.e. when the keys are different or they don't start from 1, then use either match or set the names of the 'explore_ind' with 'hex' values and then do the matching

df[] <- setNames(df2$explore_ind, df2$hex)[as.character(df)]
  • Related