首页 > 解决方案 > trying to avoid the "no non-missing arguments to min; returning Inf" warning with if_else condition does not work

问题描述

I have the following data:

df <- data.frame(x = c(1, 23, 998, 9991, 9992, 1, 2, 3),
                 group = c(1, 1, 1, 1, 1, 2, 2, 2))

df

     x group
1    1     1
2   23     1
3  998     1
4 9991     1
5 9992     1
6    1     2
7    2     2
8    3     2

I now want to go through each group separately and save the minimum of the range of values of c(998, 9991, 9992). This works for group 1, because group 1 has some values that are within c(998, 9991, 9992). Group 2 doesn't and it is expected to see a warning for group 2:

no non-missing arguments to min; returning Inf

However, in my code, I added a safety net (if else condition), where I explicitely tell the code to only calculate the minimum if the above condition of values c(998, 9991, 9992) is met. Even if I hard code to only take the minimum in group 1, I still get the above error and I don't know why.

library(tidyverse)
df %>%
  group_by(group) %>%
  mutate(test = if_else(group == 1,
                        min(x[x %in% c(998, 9991, 9992)], na.rm = TRUE),
                        NA_real_))

The result is correct, that's not the problem:

# A tibble: 8 x 3
# Groups:   group [2]
      x group  test
  <dbl> <dbl> <dbl>
1     1     1   998
2    23     1   998
3   998     1   998
4  9991     1   998
5  9992     1   998
6     1     2    NA
7     2     2    NA
8     3     2    NA

But I would have expected that the following warning wouldn't show up:

Warning message:
Problem with `mutate()` column `test`.
i `test = if_else(...)`.
i no non-missing arguments to min; returning Inf
i The warning occurred in group 2: group = 2.

Why am I still getting this warning? And is there any way to safeguard the code so that the warning wouldn't appear (i.e. apply it only to thos groups where the calculation of the minimum would be a valid action)?

标签: rwarningsmin

解决方案


推荐阅读