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