从R中的核密度估计中获取值

11

我想在R中获取对股票价格的对数密度估计。 我知道可以使用plot(density(x))进行绘图。 但实际上,我需要函数的值。

我正在尝试实现核密度估计公式。 这是我目前的进展:

a <- read.csv("boi_new.csv", header=FALSE)
S = a[,3] # takes column of increments in stock prices
dS=S[!is.na(S)] # omits first empty field

N = length(dS)                  # Sample size
rseed = 0                       # Random seed
x = rep(c(1:5),N/5)             # Inputted data

set.seed(rseed)   # Sets random seed for reproducibility

QL <- function(dS){
    h = density(dS)$bandwidth
    r = log(dS^2)
    f = 0*x
    for(i in 1:N){
        f[i] = 1/(N*h) * sum(dnorm((x-r[i])/h))
    }
    return(f)
}

QL(dS)

非常感谢任何帮助。我已经在这上面花了好几天了!


@Dason 我正在尝试寻找密度函数的值。 - Ruth O'Brien
1个回答

22

你可以直接从density函数中获取值:

x = rnorm(100)
d = density(x, from=-5, to = 5, n = 1000)
d$x
d$y

如果你真的想编写自己的核密度函数,这里有一些代码可以帮助你入门:

  1. 设置点的范围zx

z = c(-2, -1, 2)
x = seq(-5, 5, 0.01)
现在我们将把这些点添加到图表中。
plot(0, 0, xlim=c(-5, 5), ylim=c(-0.02, 0.8), 
     pch=NA, ylab="", xlab="z")
for(i in 1:length(z)) {
   points(z[i], 0, pch="X", col=2)
}
 abline(h=0)
  • 在每个点周围放置正态分布:

    ## Now we combine the kernels,
    x_total = numeric(length(x))
    for(i in 1:length(x_total)) {
      for(j in 1:length(z)) {
        x_total[i] = x_total[i] + 
          dnorm(x[i], z[j], sd=1)
      }
    }
    

    并将曲线添加到绘图中:

    lines(x, x_total, col=4, lty=2)
    
  • 最后,计算完整的估算:

  • ## Just as a histogram is the sum of the boxes, 
    ## the kernel density estimate is just the sum of the bumps. 
    ## All that's left to do, is ensure that the estimate has the
    ## correct area, i.e. in this case we divide by $n=3$:
    
    plot(x, x_total/3, 
           xlim=c(-5, 5), ylim=c(-0.02, 0.8), 
           ylab="", xlab="z", type="l")
    abline(h=0)
    

    这相应于

    density(z, adjust=1, bw=1)
    

    上述图表提供了:

    enter image description here


    非常感谢你!你真是救星啊。我已经盯着这个东西看了好几天了。真的非常感谢你! - Ruth O'Brien

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接