[R] How can I sample from a two-dimensional grid of points
Dimitris Rizopoulos
dimitris.rizopoulos at med.kuleuven.be
Mon Mar 10 15:57:00 CET 2008
you can still use sample(), e.g.,
n.grid <- 500
muA.grid <- seq(-4, 4, length = n.grid)
muB.grid <- seq(-4, 4, length = n.grid)
vals <- data.matrix(expand.grid(muA.grid, muB.grid))
mu.p <- dnorm(vals[, 1]) * dnorm(vals[, 2], sd = 0.5)
mu.p <- mu.p / sum(mu.p)
ind <- 1:nrow(vals)
samp.ind <- sample(ind, 1000, TRUE, mu.p)
mu <- vals[samp.ind, ]
head(mu, 10)
I hope it helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
http://www.student.kuleuven.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Gregory Gentlemen" <gregory_gentlemen at yahoo.ca>
To: <r-help at stat.math.ethz.ch>
Sent: Monday, March 10, 2008 3:32 PM
Subject: [R] How can I sample from a two-dimensional grid of points
> Hi everyone,
>
> My goal is to sample from a two-dimensional grid. Consider the
> following example of code:
>
> n.grid <- 500
> muA.grid <- seq(-4,4, length=n.grid)
> muB.grid <- seq(-4,4, length=n.grid)
> mu.p <- matrix(NA, nrow=n.grid, ncol=n.grid)
> for(i in 1:n.grid){
> for(j in 1:n.grid){
> mu.p[i,j] <- dnorm(muA.grid[i], 0, 1)*dnorm(muB.grid[j], 0, 0.5)
> }
> }
>
> mu.p <- mu.p/sum(mu.p)
>
> I would now like to sample the grid of points from the
> probabilities in mu.p. Im using the multivariate normal here for
> illustration as my real problem is a more complicated probability
> density. If this problem were only one-dimensional, this is easy:
>
> n.samples <- 1000
> # assuming mu.p and muA.grid are now the appropriate vectors
> mu <- sample(muA.grid, n.samples, replace=T, prob=mu.p)
>
> However, im not sure how to do this in two-dimensions in R.
>
> Thanks in advance for any help.
>
> All the best,
> Gregory Gentlemen
>
>
> ---------------------------------
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm
More information about the R-help
mailing list