I find myself often writing the following two lines. Is there a succinct alternative?
newObj <- vals
names(newObj) <- nams
# This works, but is ugly and not necessarily preferred
'names<-'(newObj <- vals, nams)
I'm looking for something similar to this (which of course does not work):
newObj <- c(nams = vals)
Wrapping it up in a function is an option as well, but I am wondering if the functionality might already be present.
sample data
vals <- c(1, 2, 3)
nams <- c("A", "B", "C")
You want the setNames function
# Your example data
vals <- 1:3
names <- LETTERS[1:3]
# Using setNames
newObj <- setNames(vals, names)
newObj
#A B C
#1 2 3
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With