为向量条目分配名称而不为向量分配变量名称? [英] Assign names to vector entries without assigning the vector a variable name?

查看:25
本文介绍了为向量条目分配名称而不为向量分配变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 中,是否可以在不先将该向量分配给变量名称的情况下为向量的组件分配名称?正常的方式显然是:

In R, is it possible to assign names to components of a vector without first assigning that vector to a variable name? The normal way is obviously:

z <- 1:3
names(z) <- c("a", "b", "c") #normal way
names(1:3) <- c("a", "b", "c") #throws an error

第二种方式抛出名称错误(1:3)<- c(a",b",c"):赋值对象扩展为非语言对象"

The second way throws "Error in names(1:3) <- c("a", "b", "c") : target of assignment expands to non-language object"

根据文档,表达式计算为

According to the doc, the expression is evaluated as

 z <- "names<-"(z,
     "[<-"(names(z), 3, "c2"))’.

所以没有震惊它不起作用,我只是想知道是否有解决方法.

So no shock it doesn't work, I'm just wondering if there's a work around.

理想情况下,最好有以下内容:

Ideally, it'd be nice to have something like:

names(z <- 1:3) <- c("a", "b", "c")
> z
a b c 
1 2 3 

把它放在两条不同的行上似乎是在浪费空间.

Just seems like a waste of space to put that on two different lines.

推荐答案

如何使用 setNames(),它看起来比您建议的理想更清晰/更清晰?

How about using setNames(), which seems even cleaner/clearer than your suggested ideal?

z <- setNames(1:3, c("a", "b", "c"))
# z
# a b c 
# 1 2 3 

这篇关于为向量条目分配名称而不为向量分配变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆