'Error in using custom vectorized function in mutate/case_when
Below is a simple code to reproduce the error. I define a simple function, vectorize it with another function using purrr::map, and then try to use it in a mutate case_when where the condition should normally ensure that the arguments are valid. The error occurs in the condition if(arg1 > 0) when arg1 = NA, but I don't understand why that even happens. If I apply the filter, the error disappears. Does anyone have an idea what I'm doing wrong? My feeling is that it should work.
require(tidyverse)
f_single <- function(arg1, arg2) {
if (arg1 > 0) {
return(arg1 * arg2)
}
}
f_vector <- function(arg1, arg2) {
result <- map2_dbl(arg1, arg2, f_single)
return(result)
}
x <- tribble(~ arg1, ~ arg2,
NA, 1,
2, 3,
4, 5,)
x %>%
# filter(!is.na(arg1)) %>%
mutate(y = case_when(arg1 > 0 ~ f_vector(arg1, arg2)))
The error is the following:
Error in `mutate()`:
! Problem while computing `y = case_when(arg1 > 0 ~ f_vector(arg1, arg2))`.
Caused by error in `if (arg1 > 0) ...`:
! missing value where TRUE/FALSE needed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
