【问题标题】:R Vectorization: How to return the index of the first element of each row in a matrix that meets a condition and sum all elements until that index?R向量化:如何返回满足条件的矩阵中每一行的第一个元素的索引并将所有元素相加,直到该索引?
【发布时间】:2016-05-06 18:22:14
【问题描述】:

我正在寻找矢量化解决方案。假设我生成了 100 个带有替换的 10 个抽签样本。接下来,我想找到累积和矩阵的第一个元素的第一个索引,这意味着某些条件,例如 >=10。然后,我想将每一行的所有元素相加,直到第一个元素的索引满足该条件。 MWE:

set <- c(1, 5, 7, 13, 15, 17)
samp <- samp <- matrix(sample(set, size = 100*10, replace = TRUE), nrow=simCount) # generate 100 samples of 10 draws
b <- matrix(apply(samp, 1, cumsum), 
  nrow = 100, byrow=TRUE) >= 10 # compare each element with 10, return boolean

我不确定如何将applywhich(x)=="TRUE" 一起使用。我尝试了一些变体,但不确定如何正确编码。

得到它之后,我将能够使用 apply(b, 1, min) 为 >=10 的每一行返回第一个元素(最小索引)。

【问题讨论】:

  • 您的 MWE 中有错字。请修复。
  • @Pascal 已修复,谢谢
  • 首先根据描述,您的带有rep 的样本不正确。也许使用:samp &lt;- matrix(sample(c(seq(1,5,1)), size = 1000, replace = TRUE), nrow=100)
  • @N8TRO 很好,谢谢!绝对不想继续重复我的抽奖。固定。
  • 我不确定b 部分是否有意义,但我将其添加到答案中只是为了彻底。

标签: r mapply


【解决方案1】:

请为“随机”示例设置种子:

set.seed(111)
samp <- matrix(sample(1:5, s=1000, r=T), nrow=100)
(answer1 <- samp[which(apply(samp,1,function(x)sum(x)>30)),1])
# [1] 4 3 3 3 1 1 3 5 2 4 2 5 4 2 4 1 3 2 4 4 5 4 2 4 5 5 4 5 3 3 1 1 2 1 4 3 4 5
#[39] 1 5 1 4 4 3 3 2 5 5

解释:

apply(samp,1, function(x) sum(x) &gt; 30)
好吧,如果您添加 10 个正整数,&gt;=10 将始终为真。 将此函数应用于每一行的“samp”。

which(x) 返回 x 的所有 TRUE 值的索引。 (感兴趣的行)

samp[(由which返回的行), (1)st column] ...基本索引

从外到内逐步展开,以便更好地理解。

b <- matrix(apply(samp, 1, cumsum), nrow=100, byrow=T)>=10
apply(b,1,function(x)which(x)[1])
#  [1] 4 5 4 3 3 5 3 4 3 4 3 3 5 4 5 4 2 4 3 6 3 3 5 4 3 3 2 4 4 6 3 4 3 4 5 4 4
# [38] 4 3 5 3 6 3 3 5 5 3 3 4 6 4 5 4 4 3 4 4 4 2 5 3 4 3 4 4 3 4 6 3 5 4 4 4 4
# [75] 3 3 5 4 4 3 3 4 4 5 4 4 4 3 4 3 5 4 3 5 3 6 4 5 5 3

【讨论】:

  • 谢谢,我会试一试,然后回复你。
  • 如何以矢量化方式对每一行的元素进行汇总,直到找到上面的索引?
【解决方案2】:

我们可以使用来自library(matrixStats)rowCumsums

library(matrixStats)
apply(rowCumsums(samp)>=10, 1, which.max)

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    相关资源
    最近更新 更多