0

使用 dplyr 可以轻松执行 group-filter-select。在下面的例子中,我们有一些公司今年不同季度的数据。我现在想过滤到第一季度没有第四季度数据的公司(在本例中是第二家公司),去掉季度标签。

df <- data.frame(companyId = c(rep(1, 4),
                               rep(2, 3),
                               rep(3, 4)),
                 Quarter = c(1:4, 1:3, 1:4),
                 Year = 2019)

q <- 4                 

df %>%
  group_by(
    companyId,
  ) %>%
  filter(
    Quarter == 1 &
      !(q %in% Quarter)
  ) %>%
  select(companyId,
         Year)

> # A tibble: 1 x 3
> # Groups:   companyId, Ticker [1]
>   companyId  Year
>       <dbl> <dbl>
> 1         2  2019

但是,对 dtplyr 执行相同操作会返回一个空表:

dt <- lazy_dt(data.table(companyId = c(rep(1, 4),
                                       rep(2, 3),
                                       rep(3, 4)),
                         Quarter = c(1:4, 1:3, 1:4),
                         Year = 2019))

q <- 4

dt %>%
  group_by(
    companyId
  ) %>%
  filter(
    Quarter == 1 &
      !(q %in% Quarter)
  ) %>%
  select(companyId
         Year)

> Source: local data table [?? x 3]
> Call:   `_DT1`[Quarter == 1 & !(q %in% Quarter), .(companyId, 
>     Year)]
> 
> # ... with 3 variables: companyId <dbl>, Year <dbl>
> 
> # Use as.data.table()/as.data.frame()/as_tibble() to access results

奇怪的是显示的翻译:

`_DT1`[Quarter == 1 & !(q %in% Quarter),
       .(companyId, Year)]

这是不正确的。如 dtplyr's own docs中所述,正确的调用需要使用过滤.SD

`_DT1`[, .SD[Quarter == 1 & !(q %in% Quarter)],
       by = .(companyId),
       .SDcols = c("Year")]

(副栏是自动包含的,所以.SDcols应该省略它们以避免重复)

有趣的是,如果我们省略select,则翻译(因此输出)是正确的:

dt %>%
  group_by(
    companyId
  ) %>%
  filter(
    Quarter == 1 &
      !(q %in% Quarter)
  )

> Source: local data table [?? x 4]
> Call:   `_DT2`[, .SD[Quarter == 1 & !(q %in% Quarter)], 
>     keyby = .(companyId)]
> 
>   companyId Quarter  Year
>       <dbl>   <int> <dbl>
> 1         2       1  2019

因此,作为一种解决方法,我可以as.data.table()select. 这可行,但会引发烦人的警告:

dt %>%
  group_by(
    companyId
  ) %>%
  filter(
    calendarQuarter == 1 &
      !(q %in% calendarQuarter)
  ) %>%
  as.data.table() %>%
  select(companyId,
         calendarYear)

>    companyId calendarYear
> 1:         2         2019
> Warning message:
> You are using a dplyr method on a raw data.table, which will call the data frame implementation,
> and is likely to be inefficient.
> * 
> * To suppress this message, either generate a data.table translation with `lazy_dt()` or convert
> * to a data frame or tibble with `as.data.frame()`/`as_tibble()`.

我很难认为这是预期的行为,但想在将其扔到dtplyrGithub 跟踪器之前检查这里。

4

1 回答 1

0

这是目前的一个错误dtplyr。我已经将它发布到包的 Github 上

于 2019-12-26T12:40:06.393 回答