我查看了其他答案,但找不到下面的代码工作的解决方案。基本上,我正在创建一个函数,该函数将两个数据帧进行inner_join
,并根据函数中输入的列对其进行filter
。
问题在于函数的filter
部分无法正常工作。 但是,如果我将过滤器从函数中删除并像mydiff("a") %>% filter(a.x != a.y)
这样追加它,则可以正常工作。
任何建议都有帮助。
请注意,我用引号括起来的是函数输入
library(dplyr)
# fake data
df1<- tibble(id = seq(4,19,2),
a = c("a","b","c","d","e","f","g","h"),
b = c(rep("foo",3), rep("bar",5)))
df2<- tibble(id = seq(10, 20, 1),
a = c("d","a", "e","f","k","m","g","i","h", "a", "b"),
b = c(rep("bar", 7), rep("foo",4)))
# What I am trying to do
dplyr::inner_join(df1, df2, by = "id") %>% select(id, b.x, b.y) %>% filter(b.x!=b.y)
#> # A tibble: 1 x 3
#> id b.x b.y
#> <dbl> <chr> <chr>
#> 1 18 bar foo
# creating a function so that I can filter by difference in column if I have more columns
mydiff <- function(filteron, df_1 = df1, df_2 = df2){
require(dplyr, warn.conflicts = F)
col_1 = paste0(quo_name(filteron), "x")
col_2 = paste0(quo_name(filteron), "y")
my_df<- inner_join(df_1, df_2, by = "id", suffix = c("x", "y"))
my_df %>% select(id, col_1, col_2) %>% filter(col_1 != col_2)
}
# the filter part is not working as expected.
# There is no difference whether i pipe filter or leave it out
mydiff("a")
#> # A tibble: 5 x 3
#> id ax ay
#> <dbl> <chr> <chr>
#> 1 10 d d
#> 2 12 e e
#> 3 14 f k
#> 4 16 g g
#> 5 18 h h
sym
,然后再使用!!
才能使其工作。很高兴知道我已经接近成功了! - x85ms16quo_name
与enquo
一起使用,您可以使函数更加灵活,因为它现在可以处理字符串和符号作为输入。 - Tung