How to use custom functions in mutate (dplyr)?

后端 未结 2 1269
既然无缘
既然无缘 2020-12-19 00:37

I\'m rewriting all my code using dplyr, and need help with mutate / mutate_at function. All I need is to apply custom function to two columns in my table. Ideally, I would r

2条回答
  •  无人及你
    2020-12-19 00:51

    Your problem seems to be binom.test instead of dplyr, binom.test is not vectorized, so you can not expect it work on vectors; You can use mapply on the two columns with mutate:

    table %>% 
        mutate(Ratio = mapply(function(x, y) binom.test.p(c(x,y)), 
                              ref_SG1_E2_1_R1_Sum, 
                              alt_SG1_E2_1_R1_Sum))
    
    #  geneId ref_SG1_E2_1_R1_Sum alt_SG1_E2_1_R1_Sum Ratio
    #1      a                  10                  10     1
    #2      b                  20                  20     1
    #3      c                  10                  10     1
    #4      d                  15                  15     1
    

    As for the last one, you need mutate_at instead of mutate:

    table %>%
          mutate_at(.vars=c(2:3), .funs=funs(sum=sum(.)))
    

提交回复
热议问题