矩阵匹配
Matrices matching
我有两个矩阵,t1
和 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"
有没有办法不用循环就可以根据tablet1
得到一个替换t2
数据的矩阵?我最后想要的矩阵是:
> t3
e1 e2 e3 e4 e5 e6 e7 e8 e9
[1,] 1 4 1 2 3 2 4 1 3
我试过 %in%
匹配,但是由于两个矩阵的长度不一样,当然它不起作用。
使用匹配
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
对于 't2' 的多行(基于@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
数据
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)))
为了笑,我在 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
(我试过t2[] <- t1[1,][t2]
,但是因为t2
本来就是一个character
矩阵,所以索引转换为:
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"
)
我有两个矩阵,t1
和 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"
有没有办法不用循环就可以根据tablet1
得到一个替换t2
数据的矩阵?我最后想要的矩阵是:
> t3
e1 e2 e3 e4 e5 e6 e7 e8 e9
[1,] 1 4 1 2 3 2 4 1 3
我试过 %in%
匹配,但是由于两个矩阵的长度不一样,当然它不起作用。
使用匹配
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
对于 't2' 的多行(基于@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
数据
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)))
为了笑,我在 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
(我试过t2[] <- t1[1,][t2]
,但是因为t2
本来就是一个character
矩阵,所以索引转换为:
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"
)