How to pass column names for inner join by 2 column sets as variables with dplyr

I've been looking at various suggested approaches for passing a column name as variable such as using bang bang (!!xvar), as.name(xvar) and various others but I can't get it to work.

Does anyone know how to pass the column names used from mtcars in the pipeline below as variables?

i.e.

xvar <- 'mpg'

yvar <- 'cyl'

to build a dummy of my data to do the join with used to determine which rows of Selected to switch T <-> F

newData <- data.frame(trace = 0, point = 1:6, 'x' = unlist(mtcars[ c(1,3,5,9:11) ,1]),  y = unlist(mtcars[ c(1,3,5,9:11) ,c('cyl')]))
rownames(newData) <- NULL

mtcars$Selected <- T

mtcars %>%
  mutate(Selected = if_else(row_number() %in% {mtcars %>% 
      mutate(rn = row_number()) %>% 
      inner_join(distinct(newData), by = c('mpg' = "x", "cyl" = 'y')) %>% 
      pull(rn)}, !Selected, Selected))

but I need to pass 'mpg' and 'cyl' as variables: xpar and ypar since they are coming from drop down menus in a Shiny App

xpar <- 'mpg' #(input$xpar_selector in shiny App)

ypar <- 'cyl' #(input$ypar_selector in shiny App)

Asked By: Mark
||

Answer #1:

An option would be to use setNames

 ...
 inner_join(distinct(newData), by = setNames(c('x', 'y'), c(xvar, var)))
 ...

Full code

mtcars %>% 
       mutate(rn = row_number()) %>% 
       inner_join(distinct(newData), by = setNames(c('x', 'y'), c(xvar, yvar))) %>% 
       pull(rn)
#[1]  1  2  3  3  5  9  9 10 11

actual full code:

mtcars %>%
  mutate(Selected = if_else(row_number() %in% {
      mtcars %>% 
        mutate(rn = row_number()) %>% 
        inner_join(distinct(newData), by = setNames(c('x', 'y'), c(xvar, yvar))) %>% 
        pull(rn)
       },
        !Selected, Selected))
Answered By: Mark
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles