Take the 2-minute tour ×

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.

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

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 
share|improve this answer
+1 Love setNames –  Joshua Ulrich Aug 2 '12 at 19:53
exactly what I was looking for, thanks! –  zzk Aug 2 '12 at 20:08
just checked, apparently set names is just a function wrapper for the 'normal way'. Still a space saver, but its not doing anything fancy. –  zzk Aug 2 '12 at 20:10
@zzk -- Yeah, I saw that too (and also noticed that it's in the stats package, oddly enough). Clearly someone else tired of not having it available in base R, and wrote it up as a little convenience function. –  Josh O'Brien Aug 2 '12 at 20:18
add comment

Your Answer


