Search code examples
rstatisticsprobabilitymodelingglm

Function To Split Probabilities :: Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test & : replacement has length zero


I am trying to split probabilities from logistic regression 'glm' model in R into different nominal categories.

I have following function.

nominal_score_test <- function(class_prob) {
             ifelse(class_prob  >= 0.00 & class_prob <= 0.38, '2.Almost Certain',
                ifelse(class_prob > 0.38 & class_prob <= 0.85, '3.Likely',
                    ifelse(class_prob > 0.85 &  class_prob <= 0.91, '3.Likely',
                        ifelse(class_prob > 0.91 & class_prob <= 1.00, '2.Almost Certain',
                                 NULL
                   ))))

}

When I apply this function to a column in a data frame I get an error.

nominal_score_test(estimates_glm_tbl$class_prob)

Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test & : 
replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :    

I am really don't understand how I can correct. Any help would be appreciated.

Thanks in advance !!!


Solution

  • Your function expects a double (class_prob argument), but in your call nominal_score_test(estimates_glm_tbl$class_prob) you give it a vector of doubles, which produces the error.

    You need to apply your nominal_score_test function individually to each element of the vector with one of the functions from the apply family. To simply return a new vector containing your descriptions try

    sapply(X = estimates_glm_tbl$class_prob, FUN = nominal_score_test)