在 Dplyr R 管道中传递多变量匿名函数

Passing a multivariable anonymous function in a Dplyr R pipe

考虑以下示例数据框

df  <- data.frame(x=c("A", "A", "B", "B"), y=c(1,2,1,2))

我正在尝试了解如何将匿名函数与管道一起使用

我想使用匿名函数创建另一种列类型

  x y  type
1 A 1 type1
2 A 2 type2
3 B 1 type2
4 B 2 type2

我当然可以使用 if_else():

df= df  %>%  mutate(type = if_else(.$x =='A' & .$y==1  , "type1",  "type2"))

但假设 if_else 函数不存在并且您想使用匿名函数:

我知道我可以像这样创建新列:

df$type =mapply(df$x,df$y, FUN=function(x,y) if ((x=='A')  && (y==1))  "type1"   else "type2")

但我也想用管道

df$type =df %>% mutate(type=mapply(.$x,.$y, FUN=function(x,y) if ((x=='A')  && (y==1))  "type1"   else "type2"))

产生以下结果:

  x y type.x type.y type.type
1 A 1      A      1     type1
2 A 2      A      2     type2
3 B 1      B      1     type2
4 B 2      B      2     type2

这给出了两个额外的不需要的列。如果我删除 .$x 和 .$y 我得到一个错误

提前致谢

这个呢?

library(magrittr)
df %<>% mutate(type=mapply(.$x,.$y, FUN=function(x,y) if ((x=='A')  && (y==1))  "type1"   else "type2"))

相当于purrr,使用map2():

df %>% mutate(type= purrr::map2(.$x,.$y, 
                                .f = function(x,y) if (x == 'A'  && y == 1) {"type1"
                                  } else {"type2"}
                                ))

虽然您实际上不必为此示例使用匿名函数。 我会在 dplyr:

中使用 case_when() 函数
df %>% mutate(type = case_when(x == "A" & y == 1 ~ "type1",
                               TRUE ~ "type2"))