I want to predict a Random Forest model onto the values from a raster stack of 20 different variables, some of which are categorical and treated as factors in the model. I uses values() to extract data from the raster stack and then as.factor() for the columns needing to be factors. But the levels of the factors do not match the levels of the new data - because of the NA values in the new data not recognized as a factor level by the model. I tried removing NA and replacing with "" nothing and that did not work.

I am not clear on using NoData versus NA or "" for raster values with no data. I guess I could add NA to factor levels in the model (rfcaret_1000) but worry that the model would then consider NA as a legitimate value?

#new data from raster stack
[1] "NA" "1"  "10" "11" "12" "13" "14" "15" "2"  "3"  "4"  "5" 
[13] "6"  "7"  "8"  "9" 

#tree learning model levels
[1] "1"  "10" "11" "12" "13" "14" "15" "2"  "3"  "4"  "5" 
[13] "6"  "7"  "8"  "9" 
  • Not having your data its hard to tell what's going on here, but when the levels function says "NA" that is not a missing value level, its a string, so it gets treated like any of the other levels. I'm not sure how this happened since we can't see how you constructed this stack. Can you make a sample dataset from scratch that shows the problem in principle?
    – Spacedman
    Mar 19 at 21:21


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.