简体   繁体   中英

R plot x,y points generated in loop

I have a for loop, that runs a function on some data.

It returns c(x,y)

I would like to plot those x,y points.

predEvaluation <- function(act,pred,thresh) {
    pred = ifelse(pred > thresh, 1, 0)
    TP = sum(pred & act)
    FP = sum(pred & !act)
    TN = sum(!pred & !act)
    FN = sum(!pred & act)
    TPR = TP/(TP + FN)
    TNR = TP/(TN + FP)
    sensitivity = TPR #how good at detecting positives
    specifity = TNR # How good at avoiding false positives
    precision = TP/(TP+FP) # how many of the positives were correct
    recall = sensitivity
    accuracy = (TP + TN)/((TP + FN) + (TN + FP)) #amount correct
    return(c(FP,TP))
}

q5 = data.frame(c(1,0,1,1,0,0,1,0,1,0),c(.98,.92,.85,.77,.71,.64,.50,.39,.34,.31))
colnames(q5) <- c("act","pred")

for(i in q5$pred)
    print(predEvaluation(q5$act,q5$pred,i))

Results in

[1] 0 1
[1] 1 1
[1] 1 2
[1] 1 3
[1] 2 3
[1] 3 3
[1] 3 4
[1] 4 4
[1] 4 5
[1] 5 5

I'm trying to get the data into one data frame, or something, and then plot it. I know there are ways to add rows to a data frame, one by one, but they're not the correct way.

Rather than using a for loop, you can use one of the apply family of functions to loop over the p5$pred values:

x <- do.call(rbind.data.frame, lapply(q5$pred, function(i) predEvaluation(q5$act,q5$pred,i)))

# or:
# x <- as.data.frame(t(sapply(q5$pred, function(i) predEvaluation(q5$act,q5$pred,i))))

names(x) <- c('pred', 'value')
plot(x)

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM