考虑以下代码:
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))
I wrote myf
回来TRUE
对于行,其中age == 34
,但这不起作用:
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
为什么这不起作用?我做错了什么吗?
EDIT:这是一个人为的、简化的示例。事实上,我的函数内部有更复杂的逻辑。
我提问的动机:
- 我以为我应该更喜欢
isTRUE(all.equal())
over ==
因为这就是 R 的做事方式。
参考文献1 http://astrostatistics.psu.edu/su07/R/html/base/html/Comparison.html, 参考2 https://stackoverflow.com/q/9508518/109941:
对于数值和复数值,请记住 == 和 != 不允许分数的有限表示,也不允许舍入误差。使用 all.equal 和 equal 几乎总是更好的选择。请参阅示例。