I'm trying to create a dataset of randomly generate values that have some specific properties:
- All positive integers greater than 0
- In two columns (x, y) that have equal sums (sum(x) == sum(y))
- Have approximately a normal distribution
I've succeeded in something that generates data close to what I want, but it is very slow. I suspect it's slow because of the while loops.
simSession <- function(sessionid = 1) {
s <- data.frame(sessionid = sessionid, userid = seq(1:12))
total <- sample(48:72, 1)
mu = total / 4
sigma = 3
s$x <- as.integer(rnorm(mean=mu, sd=sigma, n=nrow(s)))
while(sum(s$x) > total) {
# i <- sample(nrow(s), 1)
i <- sample(rep(s$userid, s$x), 1)
if(s[i, ]$x > 1) {
s[i, ]$x <- s[i, ]$x - 1
} else {
s[i, ]$x = 1
}
}
s$y <- as.integer(rnorm(mean=mu, sd=sigma, n=nrow(s)))
while(sum(s$y) > sum(s$x)) {
# i <- sample(nrow(s), 1)
i <- sample(rep(s$userid, s$y), 1)
if(s[i, ]$y > 1) {
s[i, ]$y <- s[i, ]$y - 1
} else {
s[i, ]$y = 1
}
}
s$xyr <- s$x / s$y
return(s)
}
Is there something obvious I'm missing that would make this problem easier or an alternative function that would be faster?
Also, bonus points for being able to specify a parameter that skews the mode left or right.