【问题标题】:How to fill a matrix by proportion?如何按比例填充矩阵?
【发布时间】:2020-01-22 00:15:59
【问题描述】:

我正在尝试创建一个 20x20 的矩阵,其中填充了 -1:2 的数字。但是,我不希望它是随机的,而是按我决定的比例。

例如,我希望 0.10 个单元格为 -1,0.60 个为 0,0.20 个为 1,0.10 个为 2。

这段代码能够得到一个包含我想要的所有值的矩阵,但我不知道如何编辑它来指定我想要的每个值的比例。

r <- 20
c <- 20
mat <- matrix(sample(-1:2,r*c, replace=TRUE),r,c)

【问题讨论】:

  • IN sample,有prob

标签: r for-loop matrix lapply adjacency-matrix


【解决方案1】:

我们可以使用来自sampleprob 参数

matrix(sample(-1:2,r*c, replace=TRUE, prob = c(0.1, 0.6, 0.2, 0.2)), r, c)

【讨论】:

    【解决方案2】:
    r <- 20
    c <- 20
    
    ncell = r * c
    val = c(-1, 0.2,  1, 2)
    p = c(0.1, 0.6, 0.2, 0.1)
    fill = rep(val, ceiling(p * ncell))[1:ncell]
    
    mat <- matrix(data = sample(fill), nrow = r, ncol = c)
    prop.table(table(mat))
    #> mat
    #>  -1 0.2   1   2 
    #> 0.1 0.6 0.2 0.1
    

    reprex package (v0.3.0) 于 2019 年 9 月 20 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-11
      • 2020-04-19
      • 2011-08-07
      • 1970-01-01
      • 2016-08-02
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多