使用转换表结合两个因素

时间:2013-06-26 11:15:45

标签: r matrix

我正在尝试将两个因子变量AB合并到一个“转换表”中,如下所示:

#example factors:
A <- factor(c("a","d","b"),levels=letters[1:6])
B <- factor(c("b","e","d"),levels=letters[1:5])

#translation table (columns correspond to A, rows to B):
m <- structure(c(1L, 5L, 9L, 9L, 9L, 3L, 3L, 8L, 6L, 9L, 5L, 4L, 7L, 
                 9L, 5L, 2L, 6L, 5L, 5L, 2L, 4L, 5L, 0L, 7L, 4L, 1L, 1L, 7L, 6L, 
                 3L), .Dim = 5:6, .Dimnames = list(c("a", "b", "c", "d", "e"), 
                                                   c("a", "b", "c", "d", "e", "f")))
#  a b c d e f
#a 1 3 5 2 4 1
#b 5 3 4 6 5 1
#c 9 8 7 5 0 7
#d 9 6 9 5 7 6
#e 9 9 5 2 4 3

我希望得到C <- c(5, 2, 6)作为示例因素的结果。

我的第一次尝试是C <- m[A,B],但这会导致其他内容(它不会成对地通过列表)。

1 个答案:

答案 0 :(得分:1)

如果您的矩阵为m,且您的因子为AB

m[cbind(B, A)]
相关问题