Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve Y value from density function of given X value

Tags:

r

Given a simple density histogram and curve like the one below, how can I retrieve a Y-value for a given X-value. For example the y value at mean(dat)?

dat<-c(5,7,4,6,4,3,55,6,7,5,4,3,33,44,5,2,33,22)
hist (dat,freq=F)
lines(density(dat), col="red", lwd=2)

Thanks.

like image 743
user1658170 Avatar asked Feb 12 '23 09:02

user1658170


1 Answers

You can use approxfun() with the results of density to get a function that approximates the density

dat <- c(5, 7, 4, 6, 4, 3, 55, 6, 7, 5, 4, 3, 33, 44, 5, 2, 33, 22)
hist(dat, freq=F)
lines(d<-density(dat), col="red", lwd=2)

#get density function
dd <- approxfun(d$x, d$y)
dd(mean(dat))
# [1] 0.015039

#plot results
abline(v=mean(dat), lty=2)
points(mean(dat), dd(mean(dat)), cex=1.2, pch=20, col="blue")

enter image description here

like image 181
MrFlick Avatar answered Feb 15 '23 09:02

MrFlick