【问题标题】:Uniform kernel function returning NaN返回 NaN 的统一核函数
【发布时间】:2014-12-06 23:27:03
【问题描述】:

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

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)

仅当我将函数应用于数据时(如下所示),我得到“NaN”。

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?

【问题讨论】:

    标签: r function kernel nan


    【解决方案1】:

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

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

    它按预期工作。

    【讨论】:

    • 如果你喜欢这个答案,你可以点击问题左侧的复选标记。
    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2021-05-10
    • 1970-01-01
    • 2014-01-22
    相关资源
    最近更新 更多