r - 向量化 Hmisc::partition.matrix 的输出
问题描述
我一直在尝试模拟一个持续数周的二项式过程,用于不同的池大小。我有 7 个不同的池大小,以及每周积极结果的概率。我模拟了一个伯努利过程,它每周给我一个固定数量的积极结果。我想使用partition.matrix
from 函数将这些积极结果中的每一个分配到一个池中Hmisc
,如下所示:
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_pools
上课以来list
,我尝试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])
and dim(pos_neg_pools[[1]])
are NULL
,并且 的每个元素pos_neg_pools
只能作为pos_neg_pools$`1`$`1
. 我不确定如何对该输出进行矢量化,并且我不想使用for
循环,如果我有几千个池并且每个池有 52 周的数据,这可能会很麻烦。
我该怎么办?任何帮助表示赞赏。
解决方案
您有一个列表列表,并且拆分矩阵始终位于第一个子元素下:
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
推荐阅读
- angular - TS7053:元素隐式具有“任何”类型,因为“页面”类型的表达式不能用于索引类型“对象”
- android - 从firebase实时数据库检索到的问题解组对象:第一个字段未更新
- c# - CreateLogger() 之前被调用过,只能调用一次
- laravel - Livewire:显示数据和表单的问题
- cypress - Cypress.run 设置与 zone.js 不同的标头请求
- hibernate - 有没有办法使用 JPA Criteria API/JPQL SELECT COUNT (DISTINCT col1 || col2)?
- sql - 我正在使用 Oracle SQL Developer 并希望从时间戳中提取星期几。我的语法是否正确?
- react-native - 反应原生 - 按钮不会样式
- javascript - 如何在视口中找到顶部元素?
- javascript - 关于我如何下载 mobileconfig 文件(下面的 JavaScript)或 iOS 如何处理它的问题(不确定)