Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create named vector from variables [duplicate]

Tags:

r

I want to use named vectors in a function of mine and I need the vector names from variables.

Example:

I want to create the vector

c(foo = 1, bar = -1)

in the following way:

a = "foo"
b = "bar"

c(a = 1, b = -1)

# where  c(a = 1, b = -1) == c(foo = 1, bar = -1)

Is there a way of using variables as names for vectors? Thanks in advance!

like image 655
ViktorG Avatar asked Oct 27 '25 10:10

ViktorG


1 Answers

We can use setNames

setNames(c(1, -1), c(a, b))
#  foo bar 
#  1  -1 

Or another option is lst from dplyr to create a list and then unlist

library(dplyr)
unlist(lst(!! a := 1, !! b := -1))
#   foo bar 
#   1  -1 
like image 171
akrun Avatar answered Oct 29 '25 02:10

akrun