> x<-c(1:3)
> names(x)<-c("one","two","three")
> x
one two three
1 2 3
We can do:
> names(x)<-c("one","two","three")
> x
one two three
1 2 3
> x<-setNames(c(1:3),c("one","two","three"))
> x
one two three
1 2 3
> x
one two three
1 2 3
How have I been living without this for so long!
Good to know about the function. I'll often create a named vector in one line with
ReplyDelete> x<-c(one=1,two=2,three=3)
though I'm not sure if it's as generally applicable as 'setNames'.
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:
Delete> y<-13
> x<-setNames(1:y,letters[1:y])
for instance.