Jim G. Jim G. - 20 days ago 4x
R Question

Why doesn't all.equal work within dplyr's mutate function?

Consider the following code:

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
to return
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?

EDIT: This is a contrived, simplified example. In reality, I have much more complicated logic inside of my function.

My motivation for asking:

  • I thought that I was supposed to prefer
    because that's the R way of doing things.

Reference 1, Reference 2:

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.


As @DavidArenburg said, all.equal() is not vectorized.

The following code will work:

myf <- function(age) { age == 34}