开发者

1-D conditional slice from a 2-D probability density function in R using np package

consider the included example in the np-package for r, page 21 of the Vignettes for np package. npcdens returns a conditional density object and is able to plot 2d-pdf and 2d-cdf, as shown. I wanted to know if I can somehow extract the 1-D information (pdf / cdf) from the object if I were to specify one of the two parameters, like in a vector or something ?? I am new to R and was not able to find out the format of the object. Thanks for the help. -Egon.

Here is the code as requested:

require(np)
dat开发者_Go百科a("Italy")
attach(Italy)
bw <- npcdensbw(formula=gdp~ordered(year), tol=.1, ftol=.1)

fhat <- npcdens(bws=bw)
summary(fhat)

npplot(bws=bw)

npplot(bws=bw, cdf=TRUE)
detach(Italy)


The fhat object contains all the needed info plus a whole lot more. To see what all is in there, do a str( fhat ) to see the structure.

I believe the values you are interested in are xeval, yeval, and condens (PDF density).

There are lots of ways to get at the values but I tend to like data frames. I'd pop the three vectors in a single data frame:

denDf <- cbind( year=as.character( fhat$xeval[,1] ), fhat$yeval, fhat$condens )
## had to do a dance around the year variable because it's a factor

then I'd select the values I want with a subset():

subset( denDf, year==1951 & gdp > 8 & gdp < 8.2)

since gdp is a floating point value it's very hard to select with a == operator.


The method suggested by JD Long will only extract density for data points in the existing training set. If you want the density at other points (conditioning or conditional variables) you will need to use the predict() function. The following code extracts and plots the 1-D density distribution conditioned on year ==1999, a value not contained in the original data set.

First construct a data frame with the same components as the Italy data set, with gdp regularly spaced and with "1999" an ordered factor.

yr1999<- rep("1999", 100)
gdpVals <-seq(1,35, length.out=100)
nD1999 <- data.frame(year = ordered(yr1999), gdp = gdpVals)

Next use the predict function to extract the densities.

gdpDens1999 <-predict(fhat,newdata = nD1999)

The following code plots the density.

plot(gdpVals, gdpDens1999, type='l', col='red', xlab='gdp', ylab = 'p(gdp|yr = 1999)')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜