When I run the following code section, I am getting the error message copied below.
all_data_db2 <- all_data_db2 %>%
filter (!is.na(result)) %>%
mutate(OOS=
ifelse(!is.na(lsl) & !is.na(usl) & between(result,lsl,usl), "In Spec",
ifelse (is.na(lsl) & !is.na(usl) & result <usl, "In Spec",
ifelse (!is.na(lsl) & is.na(usl) & result > lsl, "In Spec",
ifelse(is.na(lsl) & is.na(usl), "No Spec Limits",
"OOS")))))
produces error message:
Show in New WindowClear OutputExpand/Collapse Output
Error in UseMethod("rename") : no applicable method for 'rename' applied to an object of class "character"
Show in New WindowClear OutputExpand/Collapse Output
Error: Problem with mutate()
column OOS
. i OOS = ifelse(...)
. x left
must be length 1 i The error occurred in group 1: code_date = "2021-12-29". Run rlang::last_error()
to see where the error occurred.
However, when I enter values for lsl and usl in the between function only as shown below, the code runs just fine:
all_data_db2 <- all_data_db2 %>%
filter (!is.na(result)) %>%
mutate(OOS=
ifelse(!is.na(lsl) & !is.na(usl) & between(result,200,2000), "In Spec",
ifelse (is.na(lsl) & !is.na(usl) & result <usl, "In Spec",
ifelse (!is.na(lsl) & is.na(usl) & result > lsl, "In Spec",
ifelse(is.na(lsl) & is.na(usl), "No Spec Limits",
"OOS")))))
As shown above, I am using lsl and usl variable names in other parts of this code section without an issue, so very confused why they aren't working with the between() function. I also tried "as.numeric" in the between function (such as: between (result, as.numeric(lsl), as.numeric(usl)) and still got the same error message as above.
Any ideas or suggestions?
The reason is that according to ?between
, the boundary values (left
, right
) are not vectorized
left, right - Boundary values (must be scalars).
The second piece of code works only because it is a single value - scalar
and not the whole column. An option is to change the between
to comparison operators (>
, <
)
library(dplyr)
all_data_db2 <- all_data_db2 %>%
filter (!is.na(result)) %>%
mutate(OOS=
ifelse(!is.na(lsl) & !is.na(usl) & result > lsl & result <usl, "In Spec",
ifelse (is.na(lsl) & !is.na(usl) & result <usl, "In Spec",
ifelse (!is.na(lsl) & is.na(usl) & result > lsl, "In Spec",
ifelse(is.na(lsl) & is.na(usl), "No Spec Limits",
"OOS")))))
Instead of a nested ifelse
, may use case_when
all_data_db2 <- all_data_db2 %>%
filter (!is.na(result)) %>%
mutate(OOS=
case_when(!is.na(lsl) & !is.na(usl) & result > lsl &
result < usl ~ "In Spec",
is.na(lsl) & !is.na(usl) & result <usl ~ "In Spec",
!is.na(lsl) & is.na(usl) & result > lsl ~ "In Spec",
is.na(lsl) & is.na(usl) ~ "No Spec Limits",
TRUE ~ "OOS"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With