6

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") 
Dason
  • 60,663
  • 9
  • 131
  • 148
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178

2 Answers2

14

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 
Dason
  • 60,663
  • 9
  • 131
  • 148
5

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!

mnel
  • 113,303
  • 27
  • 265
  • 254
  • Very interesting. So you are saying that if I have an object that is 1GB in memory and I use `names<-` to change its name, that R will use another GB of memory to accomplish this? – Ricardo Saporta Feb 13 '13 at 05:29
  • Quite possibly, I wouldn't say always or for all object types, but especially for `data.frame` (and in the examples you posted) it did. See [this example](http://stackoverflow.com/a/13965103/1385941) (by a member of R core) which doesn't. The `data.table` package attempts to avoid much of the internal copying associated with data.frame. – mnel Feb 13 '13 at 06:05
  • 1
    +1 And there is `setnames` (lower case n) in `data.table`, too. That allows you to change particular names by name, easily; e.g. `setnames(DT,"oldbadname","New Nice Name")`. – Matt Dowle Feb 13 '13 at 11:02