Reputation: 366
I have a list of matrices, pweights
. I would like to get the column number of the maximum of each row.
My code is the following
set.seed(1)
Model_eval_Mixed <- list(AICv=1, Probabilities = matrix(sample(9,9),3,3))
Model_eval_Tan <- list(AICv=2, Probabilities = matrix(sample(9,9),3,3))
Model_eval_Exp <- list(AICv=1.5, Probabilities = matrix(sample(9,9),3,3))
Model_eval_Gau <- list(AICv=2.5, Probabilities = matrix(sample(9,9),3,3))
#models = c(Model_eval_Tan,Model_eval_Mixed,Model_eval_Gau,Model_eval_Exp)
models = list(Model_eval_Tan=Model_eval_Tan,Model_eval_Mixed=Model_eval_Mixed,Model_eval_Exp=Model_eval_Exp,Model_eval_Gau=Model_eval_Gau)
actual = c(1,2,3)
n <- length(models)
aic_min <-min(sapply(models, "[[", "AICv"))
dif <- sapply(models, "[[", "AICv")-aic_min
wts <- exp(-.5*dif)
sums <- sum(wts)
scl <- lapply(models, "[[", "Probabilities")
pweights <- lapply(1:n,function(i){scl[[i]]*wts[i]})
So in the first list, it would return a vector saying 3,3,1, with the third entries being the highest for the first two rows. And repeat for the other lists.
Upvotes: 0
Views: 38
Reputation: 4841
You can use lapply
/sapply
combined with apply
and which.max
:
lapply(pweights, apply, 1L, which.max)
#R> [[1]]
#R> [1] 3 3 1
#R>
#R> [[2]]
#R> [1] 1 3 1
#R>
#R> [[3]]
#R> [1] 1 2 1
#R>
#R> [[4]]
#R> [1] 2 3 1
sapply(pweights, apply, 1L, which.max)
#R> [,1] [,2] [,3] [,4]
#R> [1,] 3 1 1 2
#R> [2,] 3 3 2 3
#R> [3,] 1 1 1 1
This is more generic/easier to change if you want something else than the maximum. However, using max.col
as ekoam mentions is likely the way to go.
Upvotes: 1