简洁地同时分配名称和值 [英] Succinctly assign names and values simultaneously
本文介绍了简洁地同时分配名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现自己经常写以下两行.有简洁的替代方案吗?
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.
样本数据
vals <- c(1, 2, 3)
nams <- c("A", "B", "C")
推荐答案
您需要 setNames
功能
# Your example data
vals <- 1:3
names <- LETTERS[1:3]
# Using setNames
newObj <- setNames(vals, names)
newObj
#A B C
#1 2 3
这篇关于简洁地同时分配名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文