Reputation: 35331
I know that one can do something like this
x <- c(foo = 1, bar = 4)
Suppose I want to create a vector whose values and names are to be obtained from expressions such as the_values(some, args)
and the_names(some, args)
?
I know that I can create the desired vector via two assignments:
x <- the_values(some, args)
names(x) <- the_names(some, args)
Is there a way to achieve the same thing with a single assignment?
I'm also interested in the analogous question for lists.
Upvotes: 3
Views: 59
Reputation: 887881
We can use setNames
x <- setNames(the_values(some, args), the_names(some, args))
For the first example
setNames(c(1,4), c("foo", "bar"))
It would work for both list
and vector
s
setNames(list(1,4), c("foo", "bar))
Another option is names<-
x <- `names<-`(the_values(some, args), the_names(some, args))
Upvotes: 3