Mark
Mark

Reputation: 2899

Estimate and extract point values from a 3D kernel density in R

From the following code in the R documentation link I would like to figure out how to extract a single value ("density") for each of the original points of a data frame This, so that I can use the new column for further applications that i have in mind with "point" density in 3D space.

I looked at this SO issue: link, but that code give a matrix of 51 layers.. and i'm stuck how to get 150 point values instead.

In my case i'm concerned about the trivariate example that uses:

fhat <- kde(x=iris[,1:3])

This is the code, which gives a nice plot, but i'm failing to get a single value for each of the 150 rows/points in the iris data set

library(ks)
library(MASS)
data(iris)

## univariate example
fhat <- kde(x=iris[,2])
plot(fhat, cont=50, col.cont="blue", cont.lwd=2, xlab="Sepal length")

## bivariate example
fhat <- kde(x=iris[,2:3])
plot(fhat, display="filled.contour2", cont=seq(10,90,by=10))
plot(fhat, display="persp", thin=3, border=1, col="white")

## trivariate example
fhat <- kde(x=iris[,2:4])
plot(fhat, drawpoints=TRUE)

Upvotes: 0

Views: 1008

Answers (1)

Martin C. Arnold
Martin C. Arnold

Reputation: 9668

I am assuming You are referring to kde() from the ks package?

If so, use the argument eval.points to compute the density for a vector/matrix of points using the estimate:

## univariate example

library(ks)

fhat <- kde(x = iris[,2])
plot(fhat, cont=50, col.cont="blue", cont.lwd=2, xlab="Sepal length")

estimate <- kde(iris[,2], eval.points = iris[,2])$estimate
points(iris[,2], estimate)

enter image description here

Works analogously for higher input dimensions.

Upvotes: 2

Related Questions