如何在mutate(dplyr)中使用自定义函数? [英] How to use custom functions in mutate (dplyr)?

查看:414
本文介绍了如何在mutate(dplyr)中使用自定义函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用dplyr重写我的所有代码,并且需要有关mutate/mutate_at函数的帮助.我需要做的就是将自定义函数应用于表中的两列.理想情况下,我将通过它们的索引来引用这些列,但是现在我什至不能通过名称引用来使它们起作用.

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 reference these columns by their indices, but now I can't make it work even referencing by names.

函数是:

binom.test.p <- function(x) {
  if (is.na(x[1])|is.na(x[2])|(x[1]+x[2])<10) {
    return(NA)
  } 
  else {
    return(binom.test(x, alternative="two.sided")$p.value)
  }
} 

我的数据:

table <- data.frame(geneId=c("a", "b", "c", "d"), ref_SG1_E2_1_R1_Sum = c(10,20,10,15), alt_SG1_E2_1_R1_Sum = c(10,20,10,15))

所以我这样做:

table %>%
  mutate(Ratio=binom.test.p(c(ref_SG1_E2_1_R1_Sum, alt_SG1_E2_1_R1_Sum)))
Error: incorrect length of 'x'

如果我这样做:

table %>% 
mutate(Ratio=binom.test.p(ref_SG1_E2_1_R1_Sum, alt_SG1_E2_1_R1_Sum))
Error: unused argument (c(10, 20, 10, 15))

第二个错误可能是因为我的函数需要一个向量并获得两个参数.

The second error is probably because my function needs one vector and gets two parameters instead.

但是甚至忘记了我的功能.这有效:

But even forgetting about my function. This works:

table %>%
  mutate(sum = ref_SG1_E2_1_R1_Sum + alt_SG1_E2_1_R1_Sum)

这不是:

    table %>%
      mutate(.cols=c(2:3), .funs=funs(sum=sum(.)))
Error: wrong result size (2), expected 4 or 1

所以这可能是我对dplyr的工作方式的误解.

So it's probably my misunderstanding of how dplyr works.

推荐答案

您的问题似乎是binom.test而不是dplyrbinom.test没有向量化,因此不能指望它可以在向量上工作;您可以在mutate的两列上使用mapply:

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


对于最后一个,您需要mutate_at而不是mutate:


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

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

这篇关于如何在mutate(dplyr)中使用自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆