Damien Dotta
Damien Dotta

Reputation: 939

How to pass an argument in a R function that I want to use to make a join

In an R function written with the tidyverse syntax, I would like to pass as argument the name of a variable (without "") that I want to use to make a join.

My example below : Many thanks in advance !

table1 <- data.frame(
  name = c("a","b","c"),
  especes = c("setosa","versicolor","virginica")
)

mafonc <- function(var=NULL) {

  resultat <- iris %>% left_join(table1,
                                 by =  c("Species"=var))
  
  return(resultat)
}

mafonc(var=especes)

Upvotes: 1

Views: 107

Answers (1)

Duck
Duck

Reputation: 39595

Try this. You would need to use enquo() and as_label():

library(tidyverse)
#Code
table1 <- data.frame(
  name = c("a","b","c"),
  especes = c("setosa","versicolor","virginica")
)

mafonc <- function(var=NULL) {
  
  var <- enquo(var)
  resultat <- iris %>% left_join(table1,
                                 by =  c("Species"=as_label(var)))
  
  return(resultat)
}

mafonc(var=especes)

Upvotes: 1

Related Questions