sta*_*tor 8 if-statement r dplyr
一串长dplyr管道的末端是
mutate(n = if_else(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3, n))
这给出了这个错误
Error in mutate_impl(.data, dots) : Evaluation error: `false` must be type double, not integer.
Run Code Online (Sandbox Code Playgroud)
如果我改为这两个中的任何一个,那就会消失
mutate(n = ifelse(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3, n))
mutate(n = if_else(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3L, n))
我认为做一个简单的可重复娱乐是最简单的,所以我做了你在下面看到的,但我不能再得到错误了.知道发生了什么事吗?为什么不在ifelse哪里工作,如果我改变3到3L if_else,为什么if_else工作?我理解L 强制 3是一个整数,这是正确的吗?
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))
Run Code Online (Sandbox Code Playgroud)
avi*_*seR 18
if_elsefrom dplyr是类型稳定的,这意味着它检查true和false是否是同一类型,如果不是,则抛出错误.if_else在Base R中没有这样做.
写作时:
mutate(n = if_else(FiscalYear == "FY2018" & Candy == "SNICKERS", n - 3, n))
Run Code Online (Sandbox Code Playgroud)
我假设ifelse最初是一个整数类,所以n它将是整数类型,n-3强制3为double,因为if_else是double.qty并且2是不同类型的,所以typeof抛出错误.
写作时:
mutate(qty = if_else(name == "Bob" & fruit == "apple", qty / 2, qty))
Run Code Online (Sandbox Code Playgroud)
ifelse可能已经是一个双倍,所以将双倍除以ifelse(双倍)仍然会产生一倍.if_else并且if_else是相同的类型.因此没有错误.
话虽如此,可以使用以下方法轻松检查dplyr:
> typeof(6)
[1] "double"
> typeof(6L)
[1] "integer"
> typeof(6L-3)
[1] "double"
> typeof(6L-3L)
[1] "integer"
> typeof(6/2)
[1] "double"
Run Code Online (Sandbox Code Playgroud)
if_else从基础R确实隐含的胁迫,使一切同一类型,因此它不会引发错误时ifelse,并n有不同的类型.这也更危险,因为隐式强制后可能会出现意外结果.