Monday, December 10, 2012

Function setNames

I can't believe I just discovered the function setNames in the 'stats' package. All it is is a wrapper to combine the two lines of code required to create a vector & assign its names. (It can also be used to add names to other objects, such as a list.) So, for instance, instead of:
> x<-c(1:3)
> names(x)<-c("one","two","three")
> x
 one   two three
   1     2     3
We can do:
> x<-setNames(c(1:3),c("one","two","three"))
> x
 one   two three
   1     2     3

How have I been living without this for so long!

2 comments:

  1. Good to know about the function. I'll often create a named vector in one line with

    > x<-c(one=1,two=2,three=3)

    though I'm not sure if it's as generally applicable as 'setNames'.

    ReplyDelete
    Replies
    1. Good point. That works too in this example, but is not really viable for a vector indeterminate length or whose names are stored in another variable. For instance:

      > y<-13
      > x<-setNames(1:y,letters[1:y])

      for instance.

      Delete