R - 具有预定义总数的整数的随机近似正态分布

标签 r

我正在尝试创建一个随机生成具有某些特定属性的值的数据集:

  • 所有大于 0 的正整数
  • 在总和相等的两列 (x, y) 中 (sum(x) == sum(y))
  • 近似正态分布

  • 我已经成功地生成了接近我想要的数据,但速度非常慢。我怀疑它很慢,因为 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])
    

    enter image description here
    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/

    相关文章:

    R:转换为与 case_when 相同的级别顺序的因子

    r - 错误 : Must subset columns with a valid subscript vector. x 由于精度损失无法从 <double> 转换为 <integer>

    r - 如何在 R Studio 中编写字幕代码?

    r - 基于映射数据框编辑列表

    r - 使用 R 对大数据集进行变量/降维

    R:如何将矩阵每一行中的条目加倍并插入新行

    java - 保留服务器 : how to terminate a blocking instance (eval taking forever)?

    r - 使用 read.fortran 导入 .DAT 文件时出现错误

    从多个文件中随机提取视频帧

    r - 在传单包中使用 popupOptions()