Search code examples
rtidyversetidyeval

Use value inside variable in dplyrs left_join


I have a variable like this:

name = "ID"

and i want to use the value ("ID") to join a dataframe to another like this:

left_join(df1, df2, by=c(name = "col_to_join")

but I again don't know how to do this :/

with a little example

a = mtcars %>%
  select(1:3)

b = mtcars %>%
  select(3:5)

var_to_join = "disp"

# i know this could be done by just "disp"
# But the question is more on how to use a variable inside the by-argument
left_join(a, b, by = c(var_to_join = "disp"))


Solution

  • You can use stats::setNames() or rlang::set_names() to create a named vector:

    var <- "bar"
    setNames("foo", var)
    #>   bar 
    #> "foo"