【问题标题】:How to repeat sequence when condition is met满足条件时如何重复序列
【发布时间】:2017-12-06 18:07:05
【问题描述】:

我发现了这个问题的变体,我知道可以使用模数,但我很难把它们放在一起。

我有一系列按 ID 和秒的观察结果。当 id 的累计秒数增量大于 5 秒时,我想重新开始计数。有人可以帮我在 dplyr 中回答这个问题吗?

原始df

df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3), 
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df
   id val
1   1   2
2   1  10
3   1  12
4   1  15
5   1  17
6   2   2
7   2   4
8   2   7
9   2   8
10  3  12
11  3  15
12  3  20
13  3  25

期望的结果

finalResult
   id val reset
1   1   2     1
2   1  10     2
3   1  12     2
4   1  15     3
5   1  17     3
6   2   2     1
7   2   4     1
8   2   7     2
9   2   8     2
10  3  12     1
11  3  15     1
12  3  20     2
13  3  25     3

编辑

感谢昨天的回复,但我在给定的解决方案中遇到了一些问题。

在此数据集上,代码适用于某些实例。

sub.df <- structure(list(`ID` = c("1", 
                                                "1", "1", 
                                                "1", "1", 
                                                "1", "1", 
                                                "1", "1"
), dateFormat = structure(c(1479955726, 1479955726, 1483703713, 
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061
), class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")), .Names = c("ID", 
                                                                           "dateFormat"), row.names = c(NA, -9L), class = c("tbl_df", "tbl", 
                                                                                                                            "data.frame")) 

使用的解决方案:

jj <- sub.df %>% 
  group_by(`ID`) %>% 
  arrange(`ID`,`dateFormat`)%>%
  mutate(totalTimeInt = difftime(dateFormat,first(dateFormat),units = 'secs'))%>%
  mutate(totalTimeFormat   = as.numeric(totalTimeInt))%>%
  mutate(reset = cumsum(
    Reduce(
      function(x, y) 
        if (x + y >= 5) 0 
        else x + y, 

        diff(totalTimeFormat), init = 0, accumulate = TRUE
    ) == 0
  ))%>%
  mutate(reset_2 = cumsum(
    accumulate(
      diff(totalTimeFormat), 
      ~if (.x + .y >= 5) 0 else .x + .y, 
      .init = 0
    ) == 0
  ))

结果

# A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     3       3
5     1 2017-01-06 05:55:13  9680654 secs         9680654     4       4
6     1 2017-05-19 05:46:49 21167750 secs        21167750     5       5
7     1 2017-05-19 05:46:49 21167750 secs        21167750     6       6
8     1 2017-06-12 05:57:59 23242020 secs        23242020     7       7
9     1 2017-06-12 05:57:59 23242020 secs        23242020     8       8

发生的情况是,对于前两次观察,它正确地将其计为 1 个实例。当它到达第三个和第四个观察值时,这应该只算作两个观察值,因为这两个实例之间基本上没有时间过去。

正确的输出:

# A tibble: 9 x 6
# Groups:   ID [1]
     ID          dateFormat  totalTimeInt totalTimeFormat reset reset_2
  <chr>              <dttm>        <time>           <dbl> <int>   <int>
1     1 2016-09-16 05:50:59        0 secs               0     1       1
2     1 2016-09-16 05:51:01        2 secs               2     1       1
3     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
4     1 2016-11-23 20:48:46  5932667 secs         5932667     2       2
5     1 2017-01-06 05:55:13  9680654 secs         9680654     3       3
6     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
7     1 2017-05-19 05:46:49 21167750 secs        21167750     4       4
8     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5
9     1 2017-06-12 05:57:59 23242020 secs        23242020     5       5

【问题讨论】:

  • 需要注意的是,在 id group #1 中,当 val 从 12 变为 15 时,reset 会发生变化,但在 group #3 中不会。我下面的回答,和第一组的逻辑是一致的。
  • @JosephWood 那是因为在第 1 组中,此时重置的参考是 10 而对于第 3 组,它是 12
  • @duckmayr,感谢澄清这一点(即参考点不仅仅是组中的第一个值,而是前一个参考的差异大于或等于5的值) .我现在删除的答案很天真,并且错误地只提到了该组中的第一个值。

标签: r dplyr


【解决方案1】:

如果您将Reduceaccumulate = TRUE 一起使用(或purrr::accumulate,如果您愿意),您可以在大于或等于5 时重置运行差异。调用cumsum 判断该总数是否为0将返回重置次数。

library(tidyverse)

df <- data.frame(id = c(1,1,1,1,1,2,2,2,2,3,3,3,3), 
                 val = c(2,10,12,15,17,2,4,7,8,12,15,20,25))

df %>% 
    group_by(id) %>% 
    mutate(reset = cumsum(
        Reduce(
            function(x, y) if (x + y >= 5) 0 else x + y, 
            diff(val), init = 0, accumulate = TRUE
        ) == 0
    ))
#> # A tibble: 13 x 3
#> # Groups:   id [3]
#>       id   val reset
#>    <dbl> <dbl> <int>
#>  1     1     2     1
#>  2     1    10     2
#>  3     1    12     2
#>  4     1    15     3
#>  5     1    17     3
#>  6     2     2     1
#>  7     2     4     1
#>  8     2     7     2
#>  9     2     8     2
#> 10     3    12     1
#> 11     3    15     1
#> 12     3    20     2
#> 13     3    25     3

purrr::accumulate

df %>% 
    group_by(id) %>%
    mutate(reset = cumsum(
        accumulate(
            diff(val), 
            ~if (.x + .y >= 5) 0 else .x + .y, 
            .init = 0
        ) == 0
    ))
#> # A tibble: 13 x 3
#> # Groups:   id [3]
#>       id   val reset
#>    <dbl> <dbl> <int>
#>  1     1     2     1
#>  2     1    10     2
#>  3     1    12     2
#>  4     1    15     3
#>  5     1    17     3
#>  6     2     2     1
#>  7     2     4     1
#>  8     2     7     2
#>  9     2     8     2
#> 10     3    12     1
#> 11     3    15     1
#> 12     3    20     2
#> 13     3    25     3

关于编辑,问题在于某些差异为 0,这与查看重置的计数相同。最简单的解决方案是使用NA而不是零作为重置值:

library(tidyverse)

sub.df <- structure(list(`ID` = c("1", "1", "1", "1", "1", "1", "1", "1", "1"), 
                         dateFormat = structure(c(1479955726, 1479955726, 1483703713, 
                            1495190809, 1495190809, 1497265079, 1497265079, 1474023059, 1474023061), 
                            class = c("POSIXct", "POSIXt"), tzone = "America/Chicago")), 
                    .Names = c("ID", "dateFormat"), row.names = c(NA, -9L), 
                    class = c("tbl_df", "tbl", "data.frame")) 

sub.df %>% 
    group_by(ID) %>% 
    arrange(ID, dateFormat) %>%
    mutate(reset = cumsum(is.na(
               accumulate(diff(dateFormat), 
                          ~{
                              s <- sum(.x, .y, na.rm = TRUE);
                              if (s >= 5) NA else s
                          }, 
                          .init = NA)
    )))
#> # A tibble: 9 x 3
#> # Groups:   ID [1]
#>      ID          dateFormat reset
#>   <chr>              <dttm> <int>
#> 1     1 2016-09-16 05:50:59     1
#> 2     1 2016-09-16 05:51:01     1
#> 3     1 2016-11-23 20:48:46     2
#> 4     1 2016-11-23 20:48:46     2
#> 5     1 2017-01-06 05:55:13     3
#> 6     1 2017-05-19 05:46:49     4
#> 7     1 2017-05-19 05:46:49     4
#> 8     1 2017-06-12 05:57:59     5
#> 9     1 2017-06-12 05:57:59     5

最终,这种方法也面临着局限性,不过,好像任何值实际上 NA,它也会以类似方式递增。一个更健壮的解决方案是从每次迭代中返回一个包含两个元素的列表,一个用于重置总数,一个用于重置计数。不过,这需要更多的工作来实现:

sub.df %>% 
    group_by(ID) %>% 
    arrange(ID, dateFormat) %>%
    mutate(total_reset = accumulate(
        transpose(list(total = diff(dateFormat), reset = rep(0, n() - 1))),
        ~{
            s <- .x$total + .y$total;
            if (s >= 5) {
                data_frame(total = 0, reset = .x$reset + 1)
            } else {
                data_frame(total = s, reset = .x$reset)
            }
        }, 
        .init = data_frame(total = 0, reset = 1)
    )) %>% 
    unnest()
#> # A tibble: 9 x 4
#> # Groups:   ID [1]
#>      ID          dateFormat total reset
#>   <chr>              <dttm> <dbl> <dbl>
#> 1     1 2016-09-16 05:50:59     0     1
#> 2     1 2016-09-16 05:51:01     2     1
#> 3     1 2016-11-23 20:48:46     0     2
#> 4     1 2016-11-23 20:48:46     0     2
#> 5     1 2017-01-06 05:55:13     0     3
#> 6     1 2017-05-19 05:46:49     0     4
#> 7     1 2017-05-19 05:46:49     0     4
#> 8     1 2017-06-12 05:57:59     0     5
#> 9     1 2017-06-12 05:57:59     0     5

总数看起来有点傻,但如果你看一下差异,它实际上是正确的。

【讨论】:

  • 感谢您的回答。它工作得很好。但是你能解释一下Reduce 函数吗?我不明白那部分。
  • Reduce 将二进制(2 变量)函数应用于向量的连续项。默认情况下,它将所有内容折叠为一个术语,因此Reduce(`+`, 1:4)sum(1:4) 相同,尽管它计算为(((1 + 2) + 3) + 4)。但是如果加上accumulate = TRUE,就省去了中间条款,所以Reduce(`+`, 1:4, accumulate = TRUE)等价于cumsum(1:4)。它可以很好地处理列表(包括数据框),例如Reduce(`+`, mtcars),并且将接受任何复杂度的二进制函数。如果提供了init,则将其用作向量的第一个值。
  • 我遇到了解决方案的问题。如果您知道如何纠正它,我将不胜感激。谢谢。
  • @alistaire,感谢您提供彻底的解决方案。在过去的两天里我学到了很多东西,消化了你很好的答案。
  • 在这里撰写和阅读答案,以及文档。 Reduce 遵循 lapply/Map 的习语,所以一旦你搞定了,就不难推断了。 R4DS 有一些解释和练习,可能也会有帮助。
【解决方案2】:

我可能是错的(编辑:alistairebrilliant answer 证明我是错的,尽管我现在将这种方法留在这里),但我认为这是你真正需要的实例之一一个循环,因为每一行中reset 的值将取决于前几行发生的情况。我希望Joseph Wood 会想出比这更聪明的东西,但与此同时,这是一种天真的方法,它根据要求使用dplyr。我们可以做如下函数

count_resets <- function(x) {
    N <- length(x)
    value <- 1
    result <- rep(1, N)
    threshold <- x[1]
    for ( i in 2:N ) {
        if ( abs(x[i] - threshold) >= 5) {
            value <- value + 1
            threshold <- x[i]
        }
        result[i] <- value
    }
    return(result)
}

并通过id 使用dplyrgroup_by() 应用它:

library(dplyr)

df %>%
    group_by(id) %>%
    mutate(reset = count_resets(val))

# A tibble: 13 x 3
# Groups:   id [3]
      id   val reset
   <dbl> <dbl> <dbl>
 1     1     2     1
 2     1    10     2
 3     1    12     2
 4     1    15     3
 5     1    17     3
 6     2     2     1
 7     2     4     1
 8     2     7     2
 9     2     8     2
10     3    12     1
11     3    15     1
12     3    20     2
13     3    25     3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2017-04-07
    • 2020-04-21
    • 2020-03-05
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多