如何在 mutate (dplyr) 中使用自定义函数? [英] How to use custom functions in 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
而不是 dplyr
, binom.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
:
table %>%
mutate_at(.vars=c(2:3), .funs=funs(sum=sum(.)))
这篇关于如何在 mutate (dplyr) 中使用自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!