Why does `levels<-` behave differently depending on the order of named arguments?

Viewed 64
R version 4.0.2 (2020-06-22) -- "Taking Off Again" -- x86_64-pc-linux-gnu
> `levels<-`(factor(c("a", "b")), c("c", "d"))
[1] c d
Levels: c d
> args(`levels<-`)
function (x, value) 
NULL
> `levels<-`(x = factor(c("a", "b")), value = c("c", "d"))
[1] c d
Levels: c d

So far so good, and yet:

> `levels<-`(value = c("c", "d"), x = factor(c("a", "b")))
[1] "c" "d"
attr(,"levels")
[1] a b
Levels: a b

I got a different result from a call that should be equivalent. What's going on?

1 Answers

levels<- is implemented via Primitive and requires positional matching. Remove the named arguments from your last example and you get the same answer.

If you examine ?levels<- you'll see: "The replacement function is primitive". The R manual on Argument matching (found here) says that primitive functions: "typically ignore tags and do positional matching"

Related