返回NaN的统一内核函数

时间:2014-10-12 05:59:44

标签: r function kernel nan

我正在编写自己的统一内核函数,如下所示:

uniform.kernel <- function(data, predict.at, iv.name, dv.name, bandwidth){
  #Load in the DV/IV and turn them into vectors
  iv <- data$iv.name
  dv <- data$dv.name

  #Given the point we're predicting,
  #what kernel weights does each observation of the iv receive?
  kernelvalue <- ifelse(abs((iv - predict.at)/bandwidth)<= 1, 0.5,0)

  #Given these kernel values and the dv,
  #what is our estimate of the conditional expectation?
  conditional.expectation <-sum(kernelvalue*dv)/sum(kernelvalue)

  #Return the expectation
  return(conditional.expectation)
}

然后将其应用于此数据:

set.seed(101)
x <- seq(from=0, to=100, by=.1)
errors <- runif(min=.5, max=5000, n=length(x))
y <- x^2 - 3*x + errors^1.1
combo.frame <- cbind.data.frame(x,y)

仅当我将函数应用于数据(如下所示)时,我得到了#Na;&#34;。

uniform.kernel(combo.frame, 20, "x","y", 4)

但是,当我直接将函数中的步骤写入数据集(不使用函数)时,我得到了正确的答案。例如,我执行以下操作并获得正确的结果:

kernelvalue <- ifelse(abs((combo.frame$x - 20)/4)<= 1, 0.5,0)
conditional.expectation <- sum(kernelvalue*combo.frame$y)/sum(kernelvalue)

为什么我在使用该功能时会收到NaN?

1 个答案:

答案 0 :(得分:0)

您不能将$运算符与character这样的对象一起使用。请改用[运算符。替换函数中的前两行,如下所示:

  iv <- data[,iv.name]
  dv <- data[,dv.name]

它按预期工作。

相关问题