【问题标题】:Persistent Mutate Error Caused by Previous group_by/summarise由上一个 group_by/summarise 引起的持续变异错误
【发布时间】:2021-03-05 19:53:17
【问题描述】:

我看到一个由不相关代码引起的变异错误,该错误可能会导致错误被抛出或不基于正在运行的无关代码。例如,

  • 我初始化数据并成功运行了一段变异代码
  • 我运行了一个 group_by,总结了运行成功但有警告的代码块
  • 包含原始数据的相同原始代码现在会引发 mutate 错误,而它之前运行成功!
  • 我运行了一个不相关的变异,它不会影响成功运行的原始数据
  • 我现在第三次运行变异代码,现在代码再次运行成功!
library(tidyverse)
library(scales)
#> 
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#> 
#>     discard
#> The following object is masked from 'package:readr':
#> 
#>     col_factor

df_test <- tibble(group = c('a', 'a', 'b', 'b', 'b'), hour=parse_factor(as.character(c(1, 2, 1, 2, 1))), x = c(1,2,3, 4, 5), y=c(5, 6, 7, 8, 9))

return_data <- df_test %>%
  dplyr::mutate(
    hour = paste(hour, ':00'),
    across(.cols = c(x, y), scales::label_dollar())
  )

summarise_df_input <- function(.data, func, group_vars) {
  df_agg <- .data %>%
    group_by(across(all_of(group_vars))) %>%
    summarise(across(everything(), func))
  
  return(df_agg)
}

df_grouped <- df_test %>% summarise_df_input(mean, 'group')
#> Warning in mean.default(hour): argument is not numeric or logical: returning NA

#> Warning in mean.default(hour): argument is not numeric or logical: returning NA

return_data <- df_test %>%
  dplyr::mutate(
    hour = paste(hour, ':00'),
    across(.cols = c(x, y), scales::label_dollar())
  )
#> Error: Problem with `mutate()` input `..2`.
#> x subscript out of bounds
#> ℹ Input `..2` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`.

return_data <- df_test %>%
  dplyr::mutate(
    across(.cols = c(x, y), scales::label_dollar())
  )

return_data <- df_test %>%
  dplyr::mutate(
    hour = paste(hour, ':00'),
    across(.cols = c(x, y), scales::label_dollar())
  )

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

这里是正在发生的事情的代表。有谁知道发生了什么?这是使用 dplyr 1.0.5 顺便说一句。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    它使用的是everything,而应该是where(is.numeric),因为除了组列之外,还有一个“小时”列是factormean 适用于numeric 变量

    summarise_df_input <- function(.data, func, group_vars) {
      .data %>%
          group_by(across(all_of(group_vars))) %>%
           summarise(across(where(is.numeric), func), .groups = 'drop')  
      
    }
    

    -测试

    df_test %>% 
        summarise_df_input(mean, 'group')
    # A tibble: 2 x 3
    #  group     x     y
    #* <chr> <dbl> <dbl>
    #1 a       1.5   5.5
    #2 b       4     8 
    

    关于执行中的错误,可能是bug。更改across的执行顺序可以绕过错误

    return_data <- df_test %>%
        dplyr::mutate(
           across(.cols = c(x, y), scales::label_dollar()), hour = paste(hour, ':00')
      )
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 2021-10-03
      • 2019-11-03
      • 2019-11-27
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      相关资源
      最近更新 更多