你的例子是不可重现的,所以我试着这样做:
list.prob <-
list(structure(c(0.07692308, 0.38461538, 0.53846154, 0.42857143,
0.33333333, 0.23809524), .Dim = c(3L, 2L), .Dimnames = structure(list(
x = c("overcast", "rainy", "sunny"), y = c("no", "yes")), .Names = c("x",
"y"))), structure(c(0.2307692, 0.3846154, 0.3846154, 0.3333333,
0.2380952, 0.4285714), .Dim = c(3L, 2L), .Dimnames = structure(list(
x = c("cool", "hot", "mild"), y = c("no", "yes")), .Names = c("x",
"y"))))
mat <-
structure(c("sunny", "sunny", "overcast", "rainy", "hot", "hot",
"hot", "mild"), .Dim = c(4L, 2L), .Dimnames = list(NULL, c("outlook",
"temperature")))
这提供了与您开始时非常相似的内容(除了有限的 mat 仅限于那些似乎与 list.prob 中的条目相对应的列:
> list.prob
[[1]]
y
x no yes
overcast 0.07692308 0.4285714
rainy 0.38461538 0.3333333
sunny 0.53846154 0.2380952
[[2]]
y
x no yes
cool 0.2307692 0.3333333
hot 0.3846154 0.2380952
mild 0.3846154 0.4285714
> mat
outlook temperature
[1,] "sunny" "hot"
[2,] "sunny" "hot"
[3,] "overcast" "hot"
[4,] "rainy" "mild"
然后您的问题是根据list.prob 中的表翻译mat 中的每一列,但使用哪一列取决于另一个变量的值(我将其称为yesorno)。
# setup
res <- matrix(0,nrow=nrow(mat),ncol=ncol(mat))
yesorno <- "yes"
# actual computation
for (col in seq_len(ncol(mat))) {
res[,col] <- list.prob[[col]][,yesorno][mat[,col]]
}
给予
> res
[,1] [,2]
[1,] 0.2380952 0.2380952
[2,] 0.2380952 0.2380952
[3,] 0.4285714 0.2380952
[4,] 0.3333333 0.4285714
这里假设mat的第一列对应list.prob的第一个元素,以此类推;如果映射不是那么简单,那么您需要某种方式来关联它们(也许根据mat 的列名命名list.prob 的元素并循环列名以在list.prob 中进行查找) .