Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Succinctly assign names and values simultaneously

Tags:

r

assign

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") 
like image 331
Ricardo Saporta Avatar asked Feb 02 '13 22:02

Ricardo Saporta


2 Answers

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 
like image 134
Dason Avatar answered Oct 17 '22 05:10

Dason


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!

like image 25
mnel Avatar answered Oct 17 '22 03:10

mnel