R 基于累积和生成变量,并根据条件重置

R 基于累积和生成变量,并根据条件重置,r,R,我需要一个变量,例如所需的\u输出,它基于cumsumover的累积和,其中cumsum函数在每次到达阈值中的下一个数字时都会重置 cumsumover <- c(1, 2, 7, 4, 2, 5) thresh <- c(3, 7, 11) desired_output <- c(3, 3 ,7 ,11 ,11 ,11) # same length as cumsumover cut(cumsum(cumsumover),breaks = c(0, thresh[-1],

我需要一个变量,例如
所需的\u输出
,它基于
cumsumover
的累积和,其中
cumsum
函数在每次到达
阈值
中的下一个数字时都会重置

cumsumover <- c(1, 2, 7, 4, 2, 5)
thresh <- c(3, 7, 11)
desired_output <- c(3, 3 ,7 ,11 ,11 ,11) # same length as cumsumover
cut(cumsum(cumsumover),breaks = c(0, thresh[-1], max(cumsum(cumsumover))),
          labels = letters[seq_along(thresh)])

#[1] a a b c c c

cumsumover在R基中,我们可以使用
cut
breaks
作为
thresh
标签作为与
thresh
长度相同的
字母

cumsumover <- c(1, 2, 7, 4, 2, 5)
thresh <- c(3, 7, 11)
desired_output <- c(3, 3 ,7 ,11 ,11 ,11) # same length as cumsumover
cut(cumsum(cumsumover),breaks = c(0, thresh[-1], max(cumsum(cumsumover))),
          labels = letters[seq_along(thresh)])

#[1] a a b c c c
thresh
的最后一个元素替换为
max(cumsum(cumsumover))
以便将
thresh
最后一个元素之外的任何内容分配给最后一个
标签


如果我们想要
标签
作为
阈值
而不是
字母

cut(cumsum(cumsumover),breaks = c(0, thresh[-1], max(cumsum(cumsumover))),labels = thresh)
#[1] 3  3  7  11 11 11

下面是另一个解决方案:

数据:


使用
.bincode
可以执行以下操作:

thresh[.bincode(cumsum(cumsumover), c(-Inf,thresh[-1],Inf))]
[1]  3  3  7 11 11 11
.bincode
cut
使用,它基本上添加了标签和检查,因此效率更高:

 x <-rep(cumsum(cumsumover),10000)
microbenchmark::microbenchmark(
  bincode   = thresh[.bincode(x, c(-Inf,thresh[-1],Inf))],
  cut       = cut(x,breaks = c(-Inf, thresh[-1], Inf),labels = thresh))
# Unit: microseconds
#     expr    min      lq     mean  median      uq     max neval
#  bincode  450.2  459.75  654.794  482.10  642.20  5028.4   100
#      cut 1739.3 1864.90 2622.593 2215.15 2713.25 12194.8   100

x我添加了一个更一般的示例,因为我得到了一个错误:
“中断”不是唯一的
@dzgreen不建议连续更改您的问题。每个问题只能解决一个独特的问题。我建议你问一个新问题,我会问的。谢谢你的建议。
 x <-rep(cumsum(cumsumover),10000)
microbenchmark::microbenchmark(
  bincode   = thresh[.bincode(x, c(-Inf,thresh[-1],Inf))],
  cut       = cut(x,breaks = c(-Inf, thresh[-1], Inf),labels = thresh))
# Unit: microseconds
#     expr    min      lq     mean  median      uq     max neval
#  bincode  450.2  459.75  654.794  482.10  642.20  5028.4   100
#      cut 1739.3 1864.90 2622.593 2215.15 2713.25 12194.8   100