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.

Answers


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 

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 

Need Your Help

Netbeans: Automatically Select Current File in Projects

netbeans netbeans-6.9

How can I get Netbeans to automatically select (highlight) the currernt file in the Project window? Whenever I select a file in an editor tab I would like the project window to move to that file (e...

Mercurial Tagging/Branching Strategy

svn version-control mercurial

My current project is broken down into 3 parts: Website, Desktop Client, and a Plug-in for a third party program. We had started out originally with Subversion for our source control but decided to...