[英]Assign names to vector entries without assigning the vector a variable name?
In R, is it possible to assign names to components of a vector without first assigning that vector to a variable name? 在R中,是否可以在不首先将向量分配给变量名称的情况下为向量的组件分配名称? 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
The second way throws "Error in names(1:3) <- c("a", "b", "c") : target of assignment expands to non-language object" 第二种方式抛出“名称错误(1:3)<-c(“ a”,“ b”,“ c”):分配目标扩展为非语言对象”
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. 将其放在两个不同的行上似乎浪费了空间。
How about using setNames()
, which seems even cleaner/clearer than your suggested ideal? 如何使用setNames()
,它看起来比您建议的理想状态更干净/更清晰?
z <- setNames(1:3, c("a", "b", "c"))
# z
# a b c
# 1 2 3
Always thought this was a little cleaner, also don't need an additional package: 一直以为这会更清洁一点,也不需要额外的包装:
z <- c(a=1, b=2, c=3)
# z
# a b c
# 1 2 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.