I am trying to create a function sing Markov Chain to make future predictions, but it's giving me a warning message. Please help.
My R version is 3.6.1.
The issue you're having is that you're passing a vector of length > 1 to the argument t0
in rmarkovchain()
, when it expects t0
to be of length exactly one. Think about your predict function:
predict <- function(initial_state, t) {
prediction <- rmarkovchain(n = t, object = mcWeather, t0 = initial_state)[t]
prediction
}
When a vector of length greater than one is passed as the argument initial_state
, then rmarkovchain()
gets a value for t0
that is more than one element, which causes problems with markovchainSequence()
, which it calls.
Why does this cause a problem? We can see from help("markovchainSequence")
that it expects t0
is of length one:
Arguments
...[Some content omitted]...
t0 The initial state
(emphasis added). So, when it does some checking about the t0
value, it uses if()
, which expects a logical vector of only length one. That's why when it checks
if (!(t0 %in% markovchain@states))
if you've passed a vector of length more than one as t0
, you get a warning; the if()
function expects only one logical value, so it will use only the first logical value in the resulting vector. That's why you get the warning, it's also why all your predictions are the same.
So, how do we fix it? We alter your function slightly to handle vectors of length greater than one for initial_state
:
predict <- function(initial_state, t) {
prediction <- sapply(initial_state, function(state) {
rmarkovchain(n = t, object = mcWeather, t0 = state)[t]
})
return(prediction)
}
This goes across the values passed in initial_state
and predicts for them one at a time, as markovchainSequence()
would expect. We can see that it works as expected:
x <- data.frame("AccountNo" = 1:5,
"CurrentState" = c("sunny", "sunny", "rain" , "cloudy" ,"rain"),
stringsAsFactors = FALSE)
set.seed(42)
x$Prediction3 <- predict(x$CurrentState,3)
x
AccountNo CurrentState Prediction3
1 1 sunny sunny
2 2 sunny sunny
3 3 rain sunny
4 4 cloudy rain
5 5 rain sunny
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.