Reputation: 1377
I would like to create a function or object from a numeric vector that takes a numeric value as input and gives probability of presence of that value in the numeric vector. I would like to create an object like my_object
as in code below
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
I have tried using the stats::density
function to create my_object
kind of object. But the problem is that I cannot use a single value to output probability.
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)
I have to use a range, which I want to avoid
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
I hope the question is clear and makes sense. Any help is really appreciated.
Upvotes: 0
Views: 119
Reputation: 8506
You can use approxfun
for that
approx <- function(x, vec=iris$Sepal.Length, ...){
approxfun(density(vec, ...))(x)
}
approx(4.5)
#>[1] 0.1707666
approx(2, width=4)
#>[1] 0.002516293
Upvotes: 1