如何使用dplyr将2个列集的内部联接的列名作为变量传递

时间:2019-06-05 22:11:45

标签: r dplyr

我一直在研究各种建议的方法来将列名作为变量传递,例如使用bang(!! xvar),as.name(xvar)和其他各种方法,但是我无法使其正常工作。

有人知道如何在下面的管道中将<FlatList></FlatList>中使用的列名作为变量传递吗?

mtcars

xvar <- 'mpg'

为我的数据构建一个虚拟对象以进行连接,用于确定选择的哪些行切换T <-> F

yvar <- 'cyl'

但是我需要传递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)) 'mpg'作为变量:'cyl'xpar 因为它们来自ypar

中的下拉菜单

Shiny App

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

1 个答案:

答案 0 :(得分:1)

一种选择是使用setNames

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

完整代码

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

实际完整代码:

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))