【问题标题】:Vectorizing over the output of Hmisc::partition.matrix向量化 Hmisc::partition.matrix 的输出
【发布时间】:2019-12-04 10:22:39
【问题描述】:

我一直在尝试模拟一个持续数周的二项式过程,用于不同的池大小。我有 7 个不同的池大小,以及每周积极结果的概率。我模拟了一个伯努利过程,它每周给我一个固定数量的积极结果。我想使用Hmisc 中的partition.matrix 函数将这些积极结果中的每一个分配到一个池中,如下所示:

library(Hmisc)
set.seed(1)

# vector of pool sizes
pool_sizes <- c(10,15,25,35,40,45,50)

# Vector of weekly probabilities
weekly_probabilities <- c(0.12,0.37,0.68,0.43,0.2)

# weekly bernoulli trials
pos_neg <- sapply(weekly_probabilities,function(x)rbinom(sum(pool_sizes),size = 1, p = x))

# Assigning outcomes to pools
pos_neg_pools <- partition.matrix(pos_neg,rowsep = pool_sizes,colsep = 5)

我在每周获取每个池的结果数量时遇到了问题。我尝试了mapply 函数,但我收到错误消息Error in .Primitive("sum")(dots[[1L]][[1L]]) : invalid 'type' (list) of argument。由于pos_neg_poolslist 类,我尝试应用lapply 两次:

lapply(pos_neg_pools,function(x)apply(x,2,sum))

但收到此错误:

Error in apply(x, 2, sum) : dim(X) must have a positive length 

问题似乎是dim(pos_neg_pools[1])dim(pos_neg_pools[[1]])NULL,而pos_neg_pools 的每个元素只能作为pos_neg_pools$`1`$`1 访问。我不确定如何对该输出进行矢量化,并且我不想使用for 循环,如果我有几千个池,并且每个池有 52 周的数据,这可能会很麻烦。

我该怎么办?任何帮助表示赞赏。

【问题讨论】:

    标签: r hmisc


    【解决方案1】:

    你有一个list列表,分割矩阵总是在第一个子元素下:

     str(pos_neg_pools)
    List of 7
     $ 1:List of 1
      ..$ 1: int [1:10, 1:5] 0 0 0 1 0 1 1 0 0 0 ...
     $ 2:List of 1
      ..$ 1: int [1:15, 1:5] 0 0 0 0 0 0 0 1 0 0 ...
     $ 3:List of 1
      ..$ 1: int [1:25, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
     $ 4:List of 1
      ..$ 1: int [1:35, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
     $ 5:List of 1
      ..$ 1: int [1:40, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
     $ 6:List of 1
      ..$ 1: int [1:45, 1:5] 0 0 0 0 0 0 0 0 0 1 ...
     $ 7:List of 1
      ..$ 1: int [1:50, 1:5] 0 0 0 0 0 1 0 0 0 1 ...
    

    这是每个矩阵的维度:

    sapply(pos_neg_pools,function(x)dim(x[[1]]))
          1  2  3  4  5  6  7
    [1,] 10 15 25 35 40 45 50
    [2,]  5  5  5  5  5  5  5
    

    在发布的代码中,您将函数应用于列表。您需要使用以下一级:

    sapply(pos_neg_pools,function(x)colSums(x[[1]]))
    
         1  2  3  4  5  6  7
    [1,] 3  2  0  3  4  4  9
    [2,] 2  4  7  6 17 16 23
    [3,] 9 13 14 24 25 29 34
    [4,] 5  5 12 13 18 17 21
    [5,] 4  1  5  8  8 10 10
    

    或:

     lapply(pos_neg_pools,function(x)colSums(x[[1]]))
    

    为了避免这个奇怪的列表列表,因为您不需要拆分列,请执行以下操作:

    X = partition.matrix(pos_neg,rowsep = pool_sizes)
    sapply(X,colSums)
    
         1  2  3  4  5  6  7
    [1,] 3  2  0  3  4  4  9
    [2,] 2  4  7  6 17 16 23
    [3,] 9 13 14 24 25 29 34
    [4,] 5  5 12 13 18 17 21
    [5,] 4  1  5  8  8 10 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多