Hello, I have a markov chain function in R which I need to apply to every element of a large Matrix.Following is the function I have in R. Sincs it is running a bit slow (I need to run this function over a large numeber of timesteps) So, I am to used the Rcpp package to write this part of the code in C++ I can write second function ("simulateMC") in C++ but the "transitionFun" I could not. The main problem for me is the "sample" function of R, which I could not implement in Rcpp. Any help will be greatly appreciated.
################################# transitionFun = function(stateNum, oldState, probMatrix){ colnames(probMatrix) = as.character(1:stateNum-1) rownames(probMatrix) = as.character(1:stateNum-1) newState = sample(colnames(probMatrix), 1, prob = probMatrix[as.character(oldState), ]) return(newState) } tranMat = matrix(c(0.9, 0.1, 0.1, 0.9), ncol = 2); stateNum = 2; states = c(0, 1); ######Original state a 100x100 matrix of 1s and 0s. simulateMc<- function (oldMatrix, stateNum, transMat) { oldMatrix<- matrix(0, 100, 100); newMatrix<- matrix(NA, nrow(oldMatrix), ncol(oldMatrix)); for (a in 1:nrow(newMatrix)){ for(b in 1:ncol(newMatrix)){ newMatrix[a, b] = transitionFun(stateNum, oldMatrix[a, b], transMat); } } return(newMatrix); }
_______________________________________________ Rcpp-devel mailing list Rcpp-devel@lists.r-forge.r-project.org https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel