使用多个顺序访问阈值重置的累积和

问题描述 投票:1回答:1

这个问题类似于dplyr/ R cumulative sum with reset,它要求一种基于阈值重置累积总和的方法。该问题的可接受答案是应用固定阈值来重置累积的函数。

library(tidyverse)

sum_reset_at <- function(thresh) {
    function(x) {
        accumulate(x, ~if_else(.x >= thresh, .y, .x + .y))
    }
}

df <- tibble(a = c(2, 3, 1, 2, 2, 3))

df %>% mutate(c = sum_reset_at(5)(a))

## # A tibble: 6 x 2
##       a     c
##   <dbl> <dbl>
## 1     2     2
## 2     3     5
## 3     1     1
## 4     2     3
## 5     2     5
## 6     3     3

当累积达到(或超过)阈值时,它将再次从下一记录中的a值开始。

我想提供一个可以按顺序访问的阈值向量,而不是使用固定的阈值,每次重置都会递增:

thresholds <- c(5, 3, 2)

df %>% mutate(c = sum_reset_at(thresholds)(a))

## # A tibble: 6 x 2
##       a     c
##   <dbl> <dbl>
## 1     2     2
## 2     3     5
## 3     1     1
## 4     2     3
## 5     2     2
## 6     3     3

矢量将根据需要回收。

我在函数中使用sample工作:

set.seed(0)

sum_reset_at <- function(thresh) {
    function(x) {
        accumulate(x, ~if_else(.x >= sample(thresh, size = 1), .y, .x + .y))
    }
}

thresholds <- c(5, 3, 2)

df %>% mutate(c = sum_reset_at(thresholds)(a))

## # A tibble: 6 x 2
##       a     c
##   <dbl> <dbl>
## 1     2     2
## 2     3     3
## 3     1     4
## 4     2     2
## 5     2     4
## 6     3     3

但我不想随机抽样阈值,我想按顺序对它们进行采样。

r dplyr purrr
1个回答
1
投票

你可以修改sum_reset_at来接受thres的向量:

sum_reset_at <- function(thresh)
  {
    function(x) {
      i <- 1
      accumulate(x, function(.x, .y) {
        if(.x >= thresh[i])
        {
          #Increment i and return .y
          i <<- i+1
          if (i > length(thresh)) i <<- 1
          .y
        }
        else
        {
          .x + .y
        }
      })
    }
 }

df <- tibble(a = c(2, 3, 1, 2, 2, 3))

df %>% mutate(c = sum_reset_at(c(5,3,1))(a))
## A tibble: 6 x 2
#      a     c
#  <dbl> <dbl>
#1     2     2
#2     3     5
#3     1     1
#4     2     3
#5     2     5
#6     3     3
© www.soinside.com 2019 - 2024. All rights reserved.