Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

r - 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? 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"

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...