r - 给定一些条件数据,是否可以从 R 中的条件密度中采样?

标签 r sampling kernel-density

在 R 中,使用 np包,我已经创建了条件密度的带宽。我想做的是,给定一些新的条件向量,从结果分布中采样。

当前代码:

library('np')
# Generate some test data.
somedata = data.frame(replicate(10,runif(100, 0, 1)))
# Conditional variables.
X <- data.frame(somedata[, c('X1', 'X2', 'X3')])
# Dependent variables.
Y <- data.frame(somedata[, c('X4', 'X5', 'X6')])
# Warning, this can be slow (but shouldn't be too bad).
bwsome = npcdensbw(xdat=X, ydat=Y)
# TODO: Given some vector t of conditional data, how can I sample from the resulting distribution?

我对 R 很陌生,所以虽然我确实阅读了包文档,但我无法弄清楚我的愿景是否有意义或可能。如果有必要,我很乐意使用不同的包。

最佳答案

这是示例 2.49 来自:https://cran.r-project.org/web/packages/np/vignettes/np_faq.pdf ,它给出了以下
2个变量的解决方案:

###
library(np)
data(faithful)
n <- nrow(faithful)
x1 <- faithful$eruptions
x2 <- faithful$waiting
## First compute the bandwidth vector
bw <- npudensbw(~x1 + x2, ckertype = "gaussian")
plot(bw, view = "fixed", ylim = c(0, 3))
## Next generate draws from the kernel density (Gaussian)
n.boot <- 1000
i.boot <- sample(1:n, n.boot, replace = TRUE)
x1.boot <- rnorm(n.boot,x1[i.boot],bw$bw[1])
x2.boot <- rnorm(n.boot,x2[i.boot],bw$bw[2])
## Plot the density for the bootstrap sample using the original
## bandwidths
plot(npudens(~x1.boot+x2.boot,bws=bw$bw), view = "fixed")

根据@coffeejunky 的提示,以下是可能的
用 6 个变量解决您的问题:
## Generate some test data.
somedata = data.frame(replicate(10, runif(100, 0, 1)))
## Conditional variables.
X <- data.frame(somedata[, c('X1', 'X2', 'X3')])
## Dependent variables.
Y <- data.frame(somedata[, c('X4', 'X5', 'X6')])
## First compute the bandwidth vector
n <- nrow(somedata)
bw <- npudensbw(~X$X1 + X$X2 + X$X3 + Y$X4 + Y$X5 + Y$X6, ckertype = "gaussian")
plot(bw, view = "fixed", ylim = c(0, 3))
## Next generate draws from the kernel density (Gaussian)
n.boot <- 1000
i.boot <- sample(1:n, n.boot, replace=TRUE)
x1.boot <- rnorm(n.boot, X$X1[i.boot], bw$bw[1])
x2.boot <- rnorm(n.boot, X$X2[i.boot], bw$bw[2])
x3.boot <- rnorm(n.boot, X$X3[i.boot], bw$bw[3])
x4.boot <- rnorm(n.boot, Y$X4[i.boot], bw$bw[4])
x5.boot <- rnorm(n.boot, Y$X5[i.boot], bw$bw[5])
x6.boot <- rnorm(n.boot, Y$X6[i.boot], bw$bw[6])
## Plot the density for the bootstrap sample using the original
## bandwidths
ob1 <- npudens(~x1.boot + x2.boot + x3.boot + x4.boot + x5.boot + x6.boot, bws = bw$bw)
plot(ob1, view = "fixed", ylim = c(0, 3))

关于r - 给定一些条件数据,是否可以从 R 中的条件密度中采样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833038/

相关文章:

r - rmarkdown 中的传单热图

mongodb - 来自 Mongo 的随机抽样

python - 使 von Mises KDE 适应 Seaborn

R 星图较小的unit.key

r - 如果满足条件,则减去数据框中的两列

java - 在 Hadoop 中实现采样和数据挖掘算法

matlab - 使用 sinc 函数重建数字信号

python - Seaborn 概率 histplot - KDE 标准化

Python - 获取最密集点的坐标

r - R 基础对称矩阵中的图形可视化,其值为对角线