获得从核密度估计值中的R(Getting values from kernel density es

2019-08-08 11:10发布

我试图获得在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)

任何帮助将非常感激。 这一直是天!

Answer 1:

您可以直接从拉动值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) 
  2. 现在,我们将添加指向图

     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) 
  3. 把正常密度的每个点周围:

     ## 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) 
  4. 最后,计算出完整的估计:

     ## 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, ie 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) 

上面给图:



文章来源: Getting values from kernel density estimation in R