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

标签 r statistics kernel-density

我正在尝试获取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)

任何帮助将非常感激。在这里住了好几天!

最佳答案

您可以直接从density函数提取值:

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

另外,如果您确实想编写自己的内核密度函数,那么下面的一些代码可以帮助您入门:
  • 设置点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)
    

  • 上面的图给出:

    关于r - 从R中的内核密度估计获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14551610/

    相关文章:

    statistics - Tableau、散点图和趋势线显示置信水平

    machine-learning - 如何在 scikit learn 中使用核密度估计作为一维聚类方法?

    regex - R 正则表达式引擎在 3.2.0 中发生了变化?

    r - 根据列名中的匹配值和 R 中的特定列创建一个 0-1 数据框

    用于抛硬币问题的 Python 代码

    r - 计算内核双变量密度估计图下的体积

    python - 如何使 KernelDensity 归一化为 1?

    r - 有没有办法进行过滤排名来保留完整的数据框?

    regex - 删除字符串中选定单词之间的空格

    python - ks_2samp 返回 p 值 1.0