无法使用 R 在 dplyr 链中用自定义值替换 Inf

Unable to replace Inf with custom value in a dplyr chain using R

我有一个如下所示的数据框

  identifier shift_back_max shift_forward_max
  <chr>               <dbl>             <dbl>
1 11                   -140                 0
2 12                    -63               149
3 13                    -37               327
4 14                      0               193
5 16                   -Inf               Inf
6 17                   -Inf               Inf
7 18                   -Inf               Inf
8 19                   -Inf               Inf

我正在尝试用 -30 替换 -inf,用 30 替换 Inf

我尝试了下面的方法。请注意,这种情况 when 是大型 dplyr 链的一部分。但只有这一行会引发错误。所以,我在这里为一栏提供它

mutate(shift_back_max= case_when(
    (!is.na(shift_back_max)|!is.infinite(shift_back_max) ~'-30',
    TRUE ~ shift_back_max))

但是,我收到以下错误消息

Error: Problem with `mutate()` input `shift_back_max`.
x 'from' must be a finite number
i Input `shift_back_max` is `case_when(...)`.
i The error occurred in row 5.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning messages:
1: In min(shift_back_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
2: In min(shift_back_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
3: In min(shift_back_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
4: In min(shift_back_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
5: In min(shift_forward_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
6: In min(shift_forward_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
7: In min(shift_forward_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf
8: In min(shift_forward_max, na.rm = TRUE) :
  no non-missing arguments to min; returning Inf

我希望我的输出如下所示

 identifier shift_back_max shift_forward_max
  <chr>               <dbl>             <dbl>
1 11                   -140                 0
2 12                    -63               149
3 13                    -37               327
4 14                      0               193
5 16                    -30                30
6 17                    -30                30
7 18                    -30                30
8 19                    -30                30

您可以使用 ifelse() 测试一个值是否无穷大,然后在 TRUE 时将其符号乘以 30:

library(dplyr)

dat %>%
  mutate(across(starts_with("shift"), ~ ifelse(is.infinite(.x), 30 * sign(.x), .x)))

  identifier shift_back_max shift_forward_max
1         11           -140                 0
2         12            -63               149
3         13            -37               327
4         14              0               193
5         16            -30                30
6         17            -30                30
7         18            -30                30
8         19            -30                30