BladeVsResiduals
BladeVsResiduals

Reputation: 61

Matrices matching

I have two matrices, t1 and t2:

> t1
     aaa bbb ccc ddd
[1,]   1   2   3   4


> t2
     e1    e2    e3    e4    e5    e6    e7    e8    e9   
[1,] "aaa" "ddd" "aaa" "bbb" "ccc" "bbb" "ddd" "aaa" "ccc"

Is there a way to obtain a matrix that replaces the data of t2 according to the table t1 without a loop? The matrix I would like to have at the end is:

> t3
     e1 e2 e3 e4 e5 e6 e7 e8 e9
[1,]  1  4  1  2  3  2  4  1  3

I tried with the %in% matching, but as the two matrices have not the same length of course it doesn't work.

Upvotes: 1

Views: 43

Answers (2)

akrun
akrun

Reputation: 887118

Use the matching

t(setNames(t1[1,][t2[1,]], colnames(t2)))
#     e1 e2 e3 e4 e5 e6 e7 e8 e9
#[1,]  1  4  1  2  3  2  4  1  3

For multiple rows of 't2' (based on the example in @r2evans post)

out <- `dim<-`(t1[1,][t2], dim(t2))
colnames(out) <- colnames(t2)
out
#     e1 e2 e3 e4 e5 e6 e7 e8 e9
#[1,]  1  4  1  2  3  2  4  1  3
#[2,]  1  4  1  2  3  2  4  1  3

data

t1 <- t(setNames(1:4, strrep(letters[1:4], 3)))
t2 <- t(setNames(strrep(c('a', 'd', 'a', 'b', 'c', 'b', 'd', 'a', 'c'), 
            3), paste0("e", 1:9)))

Upvotes: 1

r2evans
r2evans

Reputation: 160447

For grins, I added a second row to t2:

t1 <- as.matrix(read.table(header=TRUE, row.names=1, text='
     aaa bbb ccc ddd
[1,]   1   2   3   4'))
t2 <- as.matrix(read.table(header=TRUE, row.names=1, stringsAsFactors=FALSE, text='
     e1    e2    e3    e4    e5    e6    e7    e8    e9   
[1,] "aaa" "ddd" "aaa" "bbb" "ccc" "bbb" "ddd" "aaa" "ccc"
[2,] "ddd" "ddd" "aaa" "bbb" "ccc" "bbb" "ddd" "aaa" "ccc"'))

array(t1[1,][t2], dim=dim(t2), dimnames=dimnames(t2))
#      e1 e2 e3 e4 e5 e6 e7 e8 e9
# [1,]  1  4  1  2  3  2  4  1  3
# [2,]  4  4  1  2  3  2  4  1  3

(I had tried t2[] <- t1[1,][t2], but because t2 is originally a character matrix, the indices are converted:

t2a <- t2
t2a[] <- t1[1,][t2]
t2a
#      e1  e2  e3  e4  e5  e6  e7  e8  e9 
# [1,] "1" "4" "1" "2" "3" "2" "4" "1" "3"
# [2,] "4" "4" "1" "2" "3" "2" "4" "1" "3"

)

Upvotes: 1

Related Questions