2014-10-12 92 views
0

我在写我自己的统一的内核函数,像这样:统一内核函数返回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) 

只是,当我申请的功能数据(如下),我得到“NaN”。但是,当我直接将我的函数中的步骤写入数据集(不使用函数)时,我得到了正确的答案。例如,我这样做,并得到正确的结果:当我使用功能

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

为什么我收到喃?

回答

0

您不能使用$运算符和character这样的对象。改为使用[运算符。替换你的功能中的前两行,如下所示:

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

它按预期工作。

+0

谢谢,这很好! :) – hemingway2014 2014-10-12 06:21:37

+0

如果你喜欢答案,你可以点击问题左边的复选标记。 – nograpes 2014-10-12 13:25:03

+0

完成!对不起 - 这个网站还是新手。 – hemingway2014 2014-10-13 22:28:22