如何使用dplyr通过2个列集将内部联接的列名作为变量传递 [英] How to pass column names for inner join by 2 column sets as variables with dplyr
问题描述
我一直在研究各种建议的方法来将列名作为变量传递,例如使用bang(!! xvar),as.name(xvar)和其他各种方法,但我无法使用它。
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.
有人知道如何在下面的管道中将 mtcars
中使用的列名作为变量传递吗?
Does anyone know how to pass the column names used from mtcars
in the pipeline below as variables?
即
xvar<-'mpg'
yvar<-'cyl'
构建我的数据的虚拟对象以进行连接以确定已选择的哪几行切换T <-> F
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))
但我需要通过'mpg'
和'cyl'
作为变量: xpar
和 ypar
,因为它们来自于菜单中的下拉菜单发光的应用程序
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 $ xpa闪亮的应用程序中的r_selector)
ypar<-'cyl'#(闪亮的应用程序中的input $ ypar_selector)
推荐答案
一种选择是使用 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))
这篇关于如何使用dplyr通过2个列集将内部联接的列名作为变量传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!