本文介绍了同时简洁地分配名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己经常写以下两行.有一个简洁的选择吗?

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 

这篇关于同时简洁地分配名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 00:07