【问题标题】:How to gain a function of an estimated density?如何获得估计密度的函数?
【发布时间】:2014-03-18 10:27:19
【问题描述】:

如何将密度(数据集)的结果保存为函数? 那么,如果我想评估该函数中的点 x,它会给我来自该密度(数据集)的概率?

【问题讨论】:

    标签: r function


    【解决方案1】:

    如下所示,density 函数返回一个包含 xy 密度函数值的列表,可用于使用 approxfun 函数创建“插值”函数。

    d <- density(rnorm(100))
    
    str(d)
    ## List of 7
    ##  $ x        : num [1:512] -3.85 -3.83 -3.82 -3.8 -3.79 ...
    ##  $ y        : num [1:512] 0.000135 0.000154 0.000176 0.0002 0.000227 ...
    ##  $ bw       : num 0.332
    ##  $ n        : int 100
    ##  $ call     : language density.default(x = rnorm(100))
    ##  $ data.name: chr "rnorm(100)"
    ##  $ has.na   : logi FALSE
    ##  - attr(*, "class")= chr "density"
    
    
    pdf <- approxfun(d)
    
    
    pdf(2)
    ## [1] 0.05439069
    

    approxfun 给出线性逼近

    为了验证让我们绘制原始密度d

    plot(d)
    

    现在让我们使用我们创建的新函数pdf 绘制插值

    x <- seq(-2,2,by=0.01)
    
    points(x, pdf(x))
    

    【讨论】:

    • 密度已经是一个估计值 - 进一步近似可能会带来更多的麻烦。
    • @Яaffael 确实如此。但这就是 OP 所要求的。
    • 我想这可能会有不同的看法。 OP 甚至不知道密度到底是什么——从他的问题来看。所以,从字面上看问题可能不是最好的选择。此外,他只是要求一个函数——而不是一个估计的近似值。
    • 谢谢!这正是我所需要的。很抱歉造成混淆,但我打算使用该函数,但我对密度和概率本身感到困惑。
    【解决方案2】:

    (特定点的密度值不是该点的概率。)

    > d <- density(sample(10,1000000,replace=TRUE,prob=(1:10)/sum(1:10)))
    > plot(d)
    
    # the density is estimated at a specified number of points. I find the closest to
    # the point I want to know the density's value of and then get that value.
    
    > fd <- function(x) d$y[which.min(abs(d$x - x))]
    > fd(6)
    [1] 0.311895
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2015-01-29
      • 2018-12-11
      • 2015-09-23
      • 2017-02-03
      • 1970-01-01
      • 2017-05-09
      相关资源
      最近更新 更多