【问题标题】:How to create a function from a numeric vector which takes a value as input and outputs probability of the value being present in the vector?如何从数值向量创建一个函数,该函数将一个值作为输入并输出该值存在于向量中的概率?
【发布时间】:2020-04-10 17:44:50
【问题描述】:

我想从一个数值向量创建一个函数或对象,该向量将数值作为输入,并给出该数值在数值向量中出现的概率。我想在下面的代码中创建一个像my_object 这样的对象

numeric_vector = iris$Sepal.Length
# Create a function or object from numeric vector
my_object = generate_function(iris$Sepal.Length)
prob_of_2 = my_object(2)
print(prob_of_2) # outputs probability of presence of 2 in numeric vector

我尝试使用stats::density 函数创建my_object 类对象。但问题是我不能使用单个值来输出概率。

numeric_vector = iris$Sepal.Length
my_function = data.frame(value = density(numeric_vector)$x, probability = density(numeric_vector)$y)
prob_of_2 = my_function[my_function$value == 2, ]$probability 
print(prob_of_2) # outputs numeric(0)

我必须使用一个我想避免的范围

epsilon = 1.5
prob_of_2 = sum(my_function[my_function$value >= 2 - epsilon & my_function$value <= 2 + epsilon, ]$probability)
print(prob_of_2) # outputs 0.0007896299

我希望这个问题很清楚并且有意义。非常感谢任何帮助。

【问题讨论】:

    标签: r statistics probability


    【解决方案1】:

    您可以为此使用approxfun

    approx <- function(x, vec=iris$Sepal.Length, ...){
        approxfun(density(vec, ...))(x)
    }
    approx(4.5)
    #>[1] 0.1707666
    
    approx(2, width=4)
    #>[1] 0.002516293
    

    另请参阅:https://stats.stackexchange.com/questions/78711/how-to-find-estimate-probability-density-function-from-density-function-in-r

    【讨论】:

    • 这太棒了。谢谢。
    • @penguin - 您可能不得不使用内核宽度以获得更多极端值;查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多