The names<-
method often (if not always) copies the object internally. setNames
is simply a wrapper for names<-
,
If you want to assign names and values succinctly in code and memory, then the setattr
function, from either the bit
or data.table
packages will do this by reference (no copying)
eg
library(data.table) # or library(bit)
setattr(vals, 'names', names)
Perhaps slightly less succinct, but you could write yourself a simple wrapper
name <- function(x, names){ setattr(x,'names', names)}
val <- 1:3
names <- LETTERS[1:3]
name(val, names)
# and it has worked!
val
## A B C
## 1 2 3
Note that if you assign to a new object, both the old and new object will have the names!