The end of a long string of dplyr pipes is
mutate(n = if_else(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3, n))
which gives this error
Error in mutate_impl(.data, dots) : Evaluation error: `false` must be type double, not integer.
Which goes away if I do either of these two instead
mutate(n = ifelse(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3, n))
mutate(n = if_else(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3L, n))
I thought it'd be easiest to make a simple reproducible recreation so I did what you see below, but I can't get the error anymore. Any idea what's going on? Why does ifelse
work where if_else
doesn't, and why does if_else
work if I change 3 to 3L? I understand L
coerces 3 to be an integer, is that correct?
library(tidyverse)
df <- tribble(
~name, ~fruit, ~qty,
"Bob", "apple", 10,
"Bill", "apple", 10
)
# THIS WORKS AGAIN AS IT SHOULD
df %>% mutate(qty = ifelse(name == "Bob" & fruit == "apple", qty / 2, qty))
# BUT IF_ELSE DOESN'T FAIL THIS TIME, WEIRD
df %>% mutate(qty = if_else(name == "Bob" & fruit == "apple", qty / 2, qty))
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…