r - 如何在 mutate (dplyr) 中使用自定义函数?

标签 r dplyr mutate

我正在使用 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 工作原理的误解。

最佳答案

您的问题似乎是 binom.test而不是 dplyr , binom.test不是矢量化的,所以你不能指望它在矢量上工作;您可以使用 mapplymutate 的两列上:

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(.)))

关于r - 如何在 mutate (dplyr) 中使用自定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730774/

相关文章:

r - 过滤后使用左连接更新数据

r - 如何从 R 中的一组中的最大值中找出每个组值的差异?

r - 如何在R中用一个case_when表达式改变两列?

r - 使用 ggplotly 对图例中的元素进行分组失败

r - Dplyr "Arrange"在函数内向其传递参数时函数不起作用

r - 如何将 <NULL> 单元格重新编码为 tibble 列表列中的嵌套 NA (<lgl [1]>)?

r - 在多列上提取第一个非 NA 值

r - 在ggplot R中标记geom_point

r - 警告信息 在 download.file : download had nonzero exit status

r - Dplyr select 和 group_by 在引用变量方面的区别?