Skip to content

Instantly share code, notes, and snippets.

@chiral
Last active December 29, 2015 17:19
Show Gist options
  • Select an option

  • Save chiral/7703379 to your computer and use it in GitHub Desktop.

Select an option

Save chiral/7703379 to your computer and use it in GitHub Desktop.
random sampling from arbitrary distribution with spline smoothing.
general_distribution <- function(points, step=1) {
N <- nrow(points)
L <- points[1,1]
R <- points[N,1]
U <- max(points[,2])
D <- min(points[,2])
sp <- smooth.spline(points[,1],points[,2])
x <- seq(L,R,step)
predict(sp,x)
}
general_sample <- function(pred, size=1) {
r<-rmultinom(1,size,pred$y)
rr<-c()
while (any(r>0)) {
i<-which(r>0);
rr<-c(rr,i);
r[i]<-r[i]-1;
}
return(pred$x[rr])
}
d <- general_distribution(
rbind(
c(25,10),
c(27,10),
c(28,30),
c(30,70),
c(32,50),
c(35,20),
c(40,10)
))
par(mfrow=c(2,1))
plot(d$x,d$y)
lines(d$x,d$y)
t <- general_sample(d,1000)
hist(t)
x<-factor(c("a","b"))
y<-c(2,3)
t<-general_sample(data.frame(x=x,y=y),10)
print(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment