【问题标题】:Make feature return different classes使特征返回不同的类
【发布时间】:2021-03-17 10:33:26
【问题描述】:

我正在尝试创建自己的功能,我想同时返回 POSIXctnumeric 值。我发现唯一的解决方法是在features 函数之后使用unnest()。我们可以简化这个工作流程吗?我想在我的包中包含功能,我不想让用户每次在features 之后应用unnest

示例代码

library(feasts, quietly = T, warn.conflicts = F)
library(dplyr, quietly = T, warn.conflicts = F)
library(tidyr, warn.conflicts = F, quietly = T)

  df <- data.frame(datetime = seq(c(ISOdate(2000,3,20)),
                                  by = "hour",
                                  length.out = 30),
                   group = c(rep("A", 15), rep("B", 15)),
                   x = rnorm(30))
  
  feat_event <- function(x){
    
    start <- dplyr::first(x)
    end <- dplyr::last(x)
    length <- difftime(end, start, units = "h")
    
    output <- list(
      start = unname(start),
      end = unname(end),
      length = unname(length)
    )
    
    output
  }
  
  feat_event(df$datetime)
#> $start
#> [1] "2000-03-20 12:00:00 GMT"
#> 
#> $end
#> [1] "2000-03-21 17:00:00 GMT"
#> 
#> $length
#> Time difference of 29 hours
  
  df %>% 
    as_tsibble(key = group, index = datetime) %>% 
    features(datetime, feat_event) %>% 
    unnest()
#> Warning: `cols` is now required when using unnest().
#> Please use `cols = c(start, end, length)`
#> # A tibble: 2 x 4
#>   group start               end                 length  
#>   <chr> <dttm>              <dttm>              <drtn>  
#> 1 A     2000-03-20 12:00:00 2000-03-21 02:00:00 14 hours
#> 2 B     2000-03-21 03:00:00 2000-03-21 17:00:00 14 hours

reprex package (v1.0.0) 于 2021-03-17 创建

【问题讨论】:

    标签: r tidyverse tsibble


    【解决方案1】:

    返回一个小标题而不是列表。

    feat_event <- function(x){
      
      start <- dplyr::first(x)
      end <- dplyr::last(x)
      length <- difftime(end, start, units = "h")
      
      output <- tibble(
        start = unname(start),
        end = unname(end),
        length = unname(length)
      )
      
      output
    }
    
    feat_event(df$datetime)
    # A tibble: 1 x 3
    #  start               end                 length  
    #  <dttm>              <dttm>              <drtn>  
    #1 2000-03-20 12:00:00 2000-03-21 17:00:00 29 hours
    
    df %>% 
       as_tsibble(key = group, index = datetime) %>% 
       features(datetime, feat_event)
    
    # A tibble: 2 x 4
    #  group start               end                 length  
    #  <chr> <dttm>              <dttm>              <drtn>  
    #1 A     2000-03-20 12:00:00 2000-03-21 02:00:00 14 hours
    #2 B     2000-03-21 03:00:00 2000-03-21 17:00:00 14 hours
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2014-11-24
      • 2019-08-04
      • 2020-12-31
      • 2022-07-31
      • 2015-10-29
      • 1970-01-01
      相关资源
      最近更新 更多