Applying "which.max" or any other function to every cell in a matrix in R

I have looked through all the suggestions online but I cannot get the desired result.

Here is my code:

usualviterbi<-function(x,Pi,delta,emission) 
{n <- length(x)
m <- nrow(Pi)
nu<- log(matrix(0, nrow = n, ncol = m))
phi = matrix(0, nrow = n, ncol = m) 
y <- rep(NA, n)
#Initialisation
nu[1, ] <- log(delta) + log(emission[1,])
########
#Recursion
if (n>1)
{logPi <- log(Pi)
for (i in 2:n)
{matrixnu <- matrix(nu[i - 1, ], nrow = m, ncol = m)
nu[i, ] <- apply(matrixnu + logPi, 2, max) + log(emission[i,])

phi[i,]= apply(nu[,i, drop=FALSE] - log(emission[,i,drop=FALSE]) , c(1,2), which.max)
#phi[i,]= data.frame(lapply(nu[i,] - log(emission[i,]), which.max))
}
#phi= apply(nu - log(emission), c(1,2), which.max)

########
#Termination
y[n] <- which.max(nu[n,])      #final phi
final_nu= max(nu[n,])     #final delta
######## 
#Backtracking  
for (i in seq(n - 1, 1, -1))  
  y[i] <- which.max(logPi[, y[i + 1]] + nu[i, ])}   
else {y <- which.max(nu[n,])}   #termination 
return(phi); 
#return(nu); 
#return(y)
}
x=c(1,2,3,1)
Pi=matrix(c(0.4,0.6,0.7,0.3),nrow=2, byrow=T)
delta=c(0.2,0.8)
emission=matrix(c(0.1,0.2,0,0.8,0.9,0,0.1,0.2), nrow=length(x), ncol=2, byrow=T)
usualviterbi(x,Pi,delta,emission)

I want as an output a "phi" matrix (4*2) that would tell me at which point each value in "nu" matrix occurs (i.e., I want to apply which.max to the matrix "nu"). In the "Recursion" block you can see some of my attempts but I always get errors incl. the one about the need for a positive dim length.


Ответы (0 шт):