【发布时间】:2017-11-27 14:02:35
【问题描述】:
我正在使用 dplyr 重写我的所有代码,并且需要 mutate / mutate_at 函数的帮助。我所需要的只是将自定义函数应用于表中的两列。理想情况下,我会通过它们的索引来引用这些列,但现在我无法让它工作,即使是通过名称引用。
函数是:
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))
第二个错误可能是因为我的函数需要一个向量并获取两个参数。
但甚至忘记了我的功能。这有效:
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 工作原理的误解。
【问题讨论】:
-
我不同意您的函数适用于该表。
-
@RyanMorton 你是什么意思?
-
它将始终使用这些值返回这些错误。另外,
mutate()是创建新变量,而sum()是summarise()函数。 -
@RyanMorton 在我的代码中唯一真正有效的函数是 mutate(sum = ref_SG1_E2_1_R1_Sum + alt_SG1_E2_1_R1_Sum)。所有其他人都没有,我正试图找出原因。