Reputation: 87
I am trying to implement the Epanechnikov kernel. For that I wrote the following code:
epe<-function(x){if(abs(x)<1) {1-x^2}
else {0}
}
epe(c(4,5,6,2,1,3))
epe_vec<-Vectorize(epe)
kern_epenechnikov_epe<-function(x, h, m = 512){
rg <- range(x)
xx <- seq(rg[1] - 3 * h, rg[2] + 3 * h, length.out = m)
y <- numeric(m)
for (i in seq_along(xx))
y[i] <-y[i] + epe_vec((xx[i] - x)/h))
y <- 3*y / 4
list(x = xx, y = y)
}
However, I am getting the following errors:
Error: object 'xx' not found } Error: unexpected '}' in "}"
xx is defined inside the function, I do not why R does not consider it.
I try the following implementation, it works:
kern_epenechnikov<-function(x, h, m = 512) {
rg <- range(x)
xx <- seq(rg[1] - 3 * h, rg[2] + 3 * h, length.out = m)
y <- numeric(m)
for (i in seq_along(xx))
y[i] <- y[i] + (1-((xx[i] - x)/h)^2)
y <- 3*y / 4
list(x = xx, y = y)
}
In principal, the two implementations should be similar but they are not.
Question:
How do I solve the problem on the first implementation? How does the second compare to the first
Upvotes: 0
Views: 336
Reputation: 707
It looks like a simple bracket error (you close an unopened bracket) in your first implementation.
The second example is equivalent, except that it doesn't contain a bracket error.
Can you try this? Note that I used curly brackets around the for loop, it's probably safer to use them, although they are not needed if there is only one statement in the loop.
kern_epenechnikov_epe<-function(x, h, m = 512) {
rg <- range(x)
xx <- seq(rg[1] - 3 * h, rg[2] + 3 * h, length.out = m)
y <- numeric(m)
for (i in seq_along(xx)) {
y[i] <-y[i] + epe_vec((xx[i] - x)/h) # remove second ')'
}
y <- 3*y / 4
list(x = xx, y = y)
}
By the way, such bracket errors are quickly spotted if you use curly brackets around the for loop and RStudio.
Upvotes: 2