r - 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)?
解决方案
推荐阅读
- php - 自定义查询中的日期在 Wordpress 中无法正确显示
- authentication - reSolve 框架:如何通过 HTTP 请求(routeRegisterCallback)对用户进行身份验证?
- android - Android中没有角的圆形按钮
- java - 在 JOOQ 中使用 RecordMapper 将派生列映射到 POJO
- string - 字符串操作在 tcsh 中不起作用 - 不理解子程序的变量
- swift - 如何在 Swift 中获取本地化的文件大小单位
- webserver - 如何使用 sd 卡托管 html
- python - 合并对设置为列表
- java - 如何在按下按钮时动态添加和删除多个 EditText 字段?
- python - 无法在列表中调用 max 函数