我正在尝试创建一个随机生成具有某些特定属性的值的数据集:
我已经成功地生成了接近我想要的数据,但速度非常慢。我怀疑它很慢,因为 while 循环。
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)
}
是否有明显的我遗漏的东西可以使这个问题更容易或更快的替代功能?
此外,能够指定向左或向右倾斜模式的参数的奖励积分。
最佳答案
如果您不介意期望值和方差相等,则可以使用泊松分布:
randgen <- function(n,mu) {
x <- rpois(n,mu)
y <- rpois(n,mu)
d <- sum(y)-sum(x)
if (d<0) {
ind <- sample(seq_along(y),-d)
y[ind] <- y[ind]+1
} else {
ind <- sample(seq_along(x),d)
x[ind] <- x[ind]+1
}
cbind(x=as.integer(x),y=as.integer(y))
}
set.seed(42)
rand <- randgen(1000,15)
layout(c(1,2))
qqnorm(rand[,1]); qqline(rand[,1])
qqnorm(rand[,2]); qqline(rand[,2])
is.integer(rand)
#[1] TRUE
sum(rand<0)
#[1] 0
colSums(rand)
#x y
#15084 15084
mean(rand[,1])
#[1] 15.084
mean(rand[,2])
#[1] 15.084
sd(rand[,1])
#[1] 4.086275
sd(rand[,2])
#[1] 3.741249
关于R - 具有预定义总数的整数的随机近似正态分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240195/