为什么all.equal在dplyr的mutate函数中不起作用? [英] Why doesn't all.equal work within dplyr's mutate function?
问题描述
请考虑以下代码:
library(dplyr)
patientID <- c(1, 2, 3, 4)
age <- c(25, 34, 28, 52)
diabetes <- c("Type1", "Type2", "Type1", "Type1")
status <- c("Poor", "Improved", "Excellent", "Poor")
patientdata <- data.frame(patientID, age, diabetes, status)
myf <- function(patientID, age, diabetes, status) { isTRUE(all.equal(age, 34))}
mutate(patientdata, isAge34 = myf(patientID, age, diabetes, status))
我写了 myf
返回 TRUE
表示 age == 34
的行,但这不起作用:
I wrote myf
to return TRUE
for the row where age == 34
, but this doesn't work:
patientID age diabetes status isAge34
1 1 25 Type1 Poor FALSE
2 2 34 Type2 Improved FALSE
3 3 28 Type1 Excellent FALSE
4 4 52 Type1 Poor FALSE
为什么没有用?我做错了吗?
Why didn't this work? Did I doing something wrong?
编辑:这是一个人为的简化示例。实际上,我的函数内部逻辑复杂得多。
This is a contrived, simplified example. In reality, I have much more complicated logic inside of my function.
我发问的动机:
- 我认为我应该更喜欢
isTRUE(all.equal())
而不是==
因为这是R的处理方式。
- I thought that I was supposed to prefer
isTRUE(all.equal())
over==
because that's the R way of doing things.
对于数值和复数值,请记住==和!=不允许分数的有限表示或舍入错误。将all.equal与same一起使用几乎总是可取的。请参见示例。
For numerical and complex values, remember == and != do not allow for the finite representation of fractions, nor for rounding error. Using all.equal with identical is almost always preferable. See the examples.
推荐答案
为 @ DavidArenburg说, all.equal()$ c $
As @DavidArenburg said, all.equal()
is not vectorized.
以下代码将起作用:
mutate(patientdata, isAge34 = age == 34)
这篇关于为什么all.equal在dplyr的mutate函数中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!