Coercing ... argument to logical

There is a question in "Advanced R" that intrigues me. Why is it that sum(1, 2, 3, na.omit = TRUE) yields 7. My first intuition was that na.omit is a false entry to the sum function and as the latter only takes ... as argument, na.omit = TRUE is converted to a logical and when summed upon, it's considered as 1.

What I fail to understand is why is it that it's converted to a logical ?

I do not know the answer, but I'd like to make a guess.

When you run sum(1, 2, 3, na.omit = TRUE), it tries to add 1, 2, 3 and na.omit. Among these, the last one is assigned the logical value TRUE, which is coerced into 1, because of this:

Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were integer(0) .

It is nothing specific to na.omit, you can try anything, for example avada_kevadra = 4 and it'll return 10.

> sum(harry = 1, ron = 2, hermione = 3, avada_kevadra = 4)
[1] 10

Note that none of harry, ron, hermione or avada_kevadra is defined in the global environment.


Oh thanks ! So we can kinda name the values and the function will sum upon the values...

The values don't need to be named. sum will sum all values entered. For example, try:

sum(1,2,3, na.omit=TRUE, firefly=TRUE)
sum(1, a=2, 3, na.omit=TRUE, TRUE)
sum(1, a=2, 3, na.omit=TRUE, TRUE, na.rm=TRUE)

sum doesn't have an argument called na.omit, so it treats na.omit=TRUE as just another named vector (of length one in this case). However, sum does have an argument called na.rm, so na.rm=TRUE doesn't get included in the sum.


