Reputation: 9805
I have an array of probability over a classification
post <- c(0.73,0.69,0.44,0.55,0.67,0.47,0.08,0.15,0.45,0.35)
and I want to retrieve the predicted class. right now I use
predicted <- function(post) {
function(threshold) {plyr::aaply(post, 1,
function(x) {if(x >= threshold) '+' else '-'})}}
but that seems like something R would have a syntax for.
Is there some indexing expression that would be more direct ?
Upvotes: 3
Views: 166
Reputation: 226097
As @joran suggests:
predicted <- function(post)
function(threshold)
ifelse(post>threshold,"+","-")
I find the nestedness of the functions a little confusing.
ifelse(post>threshold,"+","-")
seems sufficiently simple that you might not even need to package it in a function.
Or you could use
predicted <- function(post,threshold=0.5,alt=c("+","-"))
ifelse(post>threshold,alt[1],alt[2])
Alternatively
predicted <- function(post,threshold=0.5,alt=c("+","-"))
alt[1+(post<=threshold)]
would probably be marginally faster (post>threshold
gives a logical vector, which is coerced to 0/1 when added to 1, resulting in 1 for "below" and 2 for "above"). Or you could reverse the order of alt
, as @DWin does in his answer.
Upvotes: 6