2014-10-12 54 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