1

I am trying to write a function (glue_sth) which performs a left_join but you can specify by which variable to join, like this:

df <- tibble(x = letters[1:10])

df_aux <- tibble(z = letters[1:10], y = 1:10)

glue_sth <- function(df, variable) {

  df %>% 
    left_join(df_aux, by = c(variable = "z"))
}

In this case variable should be x but I can't make it work.

Paula
  • 497
  • 2
  • 8
  • 1
    This is a dup but I can't find it. Anyhow try `by = setNames("z",variable)` – A. Suliman Oct 14 '19 at 19:20
  • you can do that with tidy evaluation, start from here https://tidyeval.tidyverse.org/ – Matteo De Felice Oct 14 '19 at 19:21
  • 1
    Possible duplicate of [Dplyr join on by=(a = b), where a and b are variables containing strings?](https://stackoverflow.com/questions/28399065/dplyr-join-on-by-a-b-where-a-and-b-are-variables-containing-strings) – yusuzech Oct 14 '19 at 19:24
  • Possible duplicate of [dplyr \`left\_join()\` does not work with a character objects as the LHS variable](https://stackoverflow.com/questions/54823846/dplyr-left-join-does-not-work-with-a-character-objects-as-the-lhs-variable) – A. Suliman Oct 14 '19 at 19:26

1 Answers1

3

Find the function below:

glue_sth <- function(df, variable) {

  df %>% 
    dplyr::rename('join'=variable) %>% 
    dplyr::left_join(df_aux, by = c('join' = "z"))
}

Here, I have essentially renamed the column so that we do not have to go through the entire eval(parse()) route.

Alternative as described in comments:

glue_sth <- function(df, variable) {

  df %>% 
    dplyr::left_join(df_aux, by = setNames("z",variable))
}

Let me know if it works.