我有一份以下形式的列表
xx = list("a_1" = list("A", "C"),
"a_2" = list("B", "C"),
"a_3" = list("B", "B"),
"a_4" = list("C", "B"),
"a_5" = list("B", "A"),
"a_6" = list("B", "A"))
请注意,该列表包含重复的子列表,如上例中的"a_5"和"a_6".使用这个列表列表,我想要更新表单的矩阵
m = matrix(data = 0, nrow = 3, ncol = 3) # initialise matrix of zeros
rownames(m) = c("A", "B", "C") # name rows
colnames(m) = c("A", "B", "C") # name columns
使得我们将与给定对相对应的矩阵的索引加1.使用for循环很容易做到这一点
for (item in xx) {
# add one to the matrix index if item in xx
m[item[[1]], item[[2]]] = m[item[[1]], item[[2]]] + 1
}
这产生了预期的yields
A B C
A 0 0 1
B 2 1 1
C 0 1 0
不过,对于大型列表来说,这可能会有些麻烦.我希望使用apply()
个方法以向量化的方式完成这项工作,但我无法使用lapply()
的嵌套组合迭代列表,使用sapply()
的嵌套组合将值更新到矩阵.
所以我想知道如何使用apply()
的变体(S)来做到这一点?