That seems pretty funny. It seems that R extends the vector one element at a time for each unsurpassed name. Here we (a) select only the last value if the names are duplicated, and then (b) update the existing named elements and (c) add new elements
updateNamed <- function(z, z1) { z1 <- z1[!duplicated(names(z1), fromLast=TRUE)]
How does this
> z <- setNames(logical(2), c("a", 2)) > updateNamed(z, setNames(c(TRUE, FALSE, TRUE, FALSE), c("a", 2, 2, "c"))) a 2 c TRUE TRUE FALSE
and faster
> n <- 3*10^4 > z <- logical(n) > z1 <- setNames(rep(TRUE, n), as.character(1:n)) > system.time(updateNamed(z, z1)) user system elapsed 0.036 0.000 0.037
Careful consideration should be given to how names are used, for example, adding to a previously nameless vector.
> length(updateNamed(z, z1)) [1] 60000
when updating (with the "last" value) named vector
> length(updateNamed(z1, !z1)) [1] 30000
and also, as indicated in ?"[<-" , strings with zero length "" do not match.
> z = TRUE; z[""] = FALSE; z TRUE FALSE