6

我发现自己经常写以下两行。有没有简洁的替代方案?

      newObj  <- vals
names(newObj) <- nams

# This works, but is ugly and not necessarily preferred
'names<-'(newObj <- vals, nams)

我正在寻找与此类似的东西(这当然不起作用):

newObj <- c(nams = vals)

将它包装在一个函数中也是一种选择,但我想知道该功能是否已经存在。

样本数据

vals <- c(1, 2, 3)
nams <- c("A", "B", "C") 
4

2 回答 2

14

你想要的setNames功能

# Your example data
vals <- 1:3
names <- LETTERS[1:3]
# Using setNames
newObj <- setNames(vals, names)
newObj
#A B C 
#1 2 3 
于 2013-02-02T22:17:32.547 回答
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!

于 2013-02-13T05:20:54.207 回答