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

时间:2017-05-16 15:55:37

标签: r anonymous-function

考虑以下示例数据框

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

它会产生两个额外的不需要的colunms。如果我删除。$ x和。$ y我收到错误

提前谢谢

2 个答案:

答案 0 :(得分:1)

这个怎么样?

stringReverse proc;     <-- Warning: EBX and ESI are not preserved!
  push ebp;
  mov ebp, esp;
  mov ebx, [ebp + 8];   <-- EBX = target string pointer
  push ebx;
  call stringLength;    <-- we trust that stringLength() preserves EBX
;  mov ebx, [ebp + 8];   <-- uncomment this if it actually does not
  mov esi, ebx;
  xor edx, edx;
  add ebx, eax;
  neg eax;

  @fill:
    mov cl, [ebx + eax];
    sub esp, 8;         <-- allocating a new linked list item on stack
    mov [esp], cl;      <-- 1st DWORD / 1st BYTE = current character
    mov [esp + 4], edx; <-- 2nd DWORD = next item pointer
    mov edx, esp;       <-- EDX = current item pointer
    inc eax;
  jne @fill;

  @roll:
    mov cl, [edx];
    mov [esi], cl;
    inc esi;
    mov edx, [edx + 4]; <-- next item, here we go!
    test edx, edx;      <-- what if we are done?
  jne @roll;

  mov esp, ebp;         <-- discarding the allocated stack
  pop ebp;
  ret 4;

答案 1 :(得分:0)

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