在具有多个参数的用户定义函数上使用 apply/sapply

Using apply/sapply on a user defined function with multiple parameters

我正在为一个大学项目编写决策树算法。为此,我为确定最佳拆分的数字变量编写了一个函数。当我给它输入变量时,这个函数可以正常工作。 split的选择是根据gini指数。

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]

如此有效:

credit.dat <- read.csv("http://www.cs.uu.nl/docs/vakken/mdm/credit.txt")
y <- credit.dat[, 6]

sapply(credit.dat, FUN=best.split.point, y=y)
# > sapply(credit.dat, best.split.point, y=y)
#     age married   house  income  gender   class 
#    32.5     0.5     0.5    36.0     0.5     0.5