简体   繁体   中英

R: Sample data from model, package `ks`

I'm sorry if this has an obvious answer someplace, I haven't been able to find one and I'm not too experienced with R.

I'm using the kernel-smoothing package ks to produce a kernel-density estimation model using kde . I would like to then sample the model produced.

library(ks)
data <- read.table("data_file.txt", header=FALSE)
model <- kde(data)

And then I'm not sure how to proceed. I had read the help document but hadn't found the necessary function.

Univariate case

Please refer to the help document: https://cran.r-project.org/web/packages/ks/ks.pdf

You can see dkde , pkde , qkde , rkde as same as any R distribution.

rkde(100, model)

It'll generate 100 random number from estimated distribution.

Multivariate case

I'm surprised finding ks package whick don't prodive sample method directly. Anyway it's easily in principle. You only need first to select randomly a sample point and then to apply a estimated kernel noise on it. For slow but basic code example with multivariate normal kernel:

library(mvtnorm)

rmkde <- function(size,flat){
  n <- nrow(flat$x)
  s <- sample(1:n,size,replace=TRUE)
  t(apply(flat$x[s,],1,function(mean)rmvnorm(1,mean=mean,sigma=flat$H)))
}

rmkde(100, model)

Since rmvnorm compute same matrix decomposition many times, it is slow, you can pick decomposition from rmvnorm source code to accelerate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM