【发布时间】:2018-09-24 12:53:40
【问题描述】:
对于一个大学项目,我正在编写一个决策树算法。为此,我为确定最佳分割的数值变量编写了一个函数。当我给它输入变量时,这个函数可以正常工作。拆分的选择基于基尼指数。
gini.index <- function(input){
l <- length(input)
som <- sum(input)
probability <- 1 - som/l
gini <- probability * (1-probability)
gini
}
impurity.reduction <- function(y, yl,yr){
pi.l <- length(yl)/length(y)
pi.r <- length(yr)/length(y)
imp.red <- gini.index(y) - (pi.l * gini.index(yl) + pi.r * gini.index(yr))
imp.red
}
best.split.point <- function(x,y){
if (length(x) == length(y)){
#bekijk mogelijke numerieke waarden om op te splitten
x.sorted <- sort(unique(x))
x.sorted.length <- length(x.sorted)
splitpoints <- (x.sorted[1:(x.sorted.length-1)]+x.sorted[2:x.sorted.length])/2
splitpoints
#creer een lege vector om in de for loop alle impurity reduction waarden per split op te kunnen slaan
puur <- vector()
#bekijk voor ieder splitpoint wat de impurity reduction is
for (i in 1:length(splitpoints)) {
y1 <- y[x < splitpoints[i]]
y2 <- y[x >= splitpoints[i]]
puur <- c(puur,impurity.reduction(y,y1,y2))
}
splitpoints[puur == max(puur)]
}
else {
return("Variables X & Y need to be of the same length")
}
}
当我尝试使用以下命令找出数据集中每个单独列的最佳特征拆分是什么时,我收到以下错误:
sapply(credit.dat, best.split.point(credit.dat, y))
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'Variables X & Y need to be of the same length' of mode 'function' was not found
其他一些帖子表明这可能是由于我的函数的命名(我已经更改了)。我认为该错误可能与我的功能组成有关。你们中的哪一位可以帮我找出导致此错误弹出的原因吗?
信用数据集可在此处获得:http://www.cs.uu.nl/docs/vakken/mdm/credit.txt y变量是信用数据集的第六列,所以:
credit.dat <- read.csv("http://www.cs.uu.nl/docs/vakken/mdm/credit.txt")
y <- credit.dat[, 6]
【问题讨论】:
-
sapply()的示例:sapply(iris[-5], FUN=mean)(not FUN=mean(...)) 但这不是唯一的错误。credit.dat是什么对象?它是一个数据框吗?如果是,那么sapply()正在处理它的列(一个接一个)。 -
那么
apply()的FUN部分函数的多个输入参数的解决方案是什么?best.split.point需要两个参数。credit.dat是一个数据框。很高兴听到它应该在列上一一工作!这就是它应该做的。信用数据集可在原始帖子的链接中找到。 @jogo -
将附加参数传递给
sapply可以使用...处理,请查看此帖子以获取示例r-bloggers.com/using-apply-sapply-lapply-in-r