简体   繁体   English

在 R 中绘制函数时出现奇怪的错误

[英]Strange error while plotting function in R

I have the following function:我有以下功能:

cost<-function(alpha) {
  ypred<-lda.pred$posterior[,2] # prob of Y=1
  ypred[lda.pred$posterior[,2]>=alpha]=1
  ypred[lda.pred$posterior[,2]<alpha]=0
  y<-dataframe_testsample[,y]
  df<-data.frame(y,ypred)
  row.names(df) <- NULL
  FN <- sum(df$y == '1' & df$ypred == '0')
  FP <- sum(df$y == '0' & df$ypred == '1')
  tot_costs<-FN*10+FP*8
  return(tot_costs)
  }

This is a function to calculate the total costs of a wrong classification of a class while using the Linear Discriminant Analysis (lda command in R).这是一个函数,用于在使用线性判别分析(R 中的 lda 命令)时计算错误分类的总成本。 y and ypred are both 137x1 vectors. yypred都是 137x1 向量。 The function calculates the number of false positive (FP) and false negative (FN) and also the total cost.该函数计算假阳性 (FP) 和假阴性 (FN) 的数量以及总成本。 This works flwaless.这工作顺利。 However, when trying to plot it with the following但是,当尝试使用以下内容绘制它时

alpha_grid<-seq(0,1,0.01)
plot(alpha_grid,cost(alpha_grid))

I get the following error message:我收到以下错误消息:

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' and 'y' lengths differ
Inoltre: Warning messages:
1: In lda.pred$posterior[, 2] >= alpha :
  longer object length is not a multiple of shorter object length
2: In lda.pred$posterior[, 2] < alpha :
  longer object length is not a multiple of shorter object length

What is it happening here?这里发生了什么?

Your function deals with a single value of alpha at the moment.您的函数目前处理单个 alpha 值。 You could get the result you want by using sapply你可以通过使用 sapply 得到你想要的结果

alpha_grid<-seq(0,1,0.01)
plot(alpha_grid,sapply(alpha_grid, FUN=cost))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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