Succinctly assign names and values simultaneously

拥有回忆 提交于 2019-12-04 22:50:57

问题


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") 

回答1:


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 



回答2:


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!



来源:https://stackoverflow.com/questions/14667088/succinctly-assign-names-and-values-simultaneously

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!