这是使用dplyr::rowwise 的tidyverse 解决方案。我使用了您的原始语法以及@StupidWolf 的矩阵建议。在您非常小的数据集上,它的速度似乎大约是原来的两倍。
# https://stackoverflow.com/questions/61371610/apply-function-over-dataframe-including-rbind-statement
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
testdf<-data.frame(a=c(80,1,3,4),b=c(100,200,300,400),c=c(1,2,3,4),d=c(200,250,350,450))
for (i in 1:nrow(testdf)){
testdf$e[i] <- fisher.test(rbind(c(testdf$a[i],testdf$b[i]),c(testdf$c[i],testdf$d[i])))$p.value
}
testdf <- testdf %>%
distinct() %>%
rowwise() %>%
mutate(pvalue1 = fisher.test(rbind(c(a, b),
c(c, d)))$p.value)
testdf <- testdf %>%
distinct() %>%
rowwise() %>%
mutate(pvalue2 = fisher.test(matrix(c(a, b, c, d),
ncol = 2))$p.value)
testdf
#> Source: local data frame [4 x 7]
#> Groups: <by row>
#>
#> # A tibble: 4 x 7
#> a b c d e pvalue1 pvalue2
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 80 100 1 200 3.00e-30 3.00e-30 3.00e-30
#> 2 1 200 2 250 1.00e+ 0 1.00e+ 0 1.00e+ 0
#> 3 3 300 3 350 1.00e+ 0 1.00e+ 0 1.00e+ 0
#> 4 4 400 4 450 1.00e+ 0 1.00e+ 0 1.00e+ 0
all.equal(testdf$e, testdf$pvalue1)
#> [1] TRUE
all.equal(testdf$e, testdf$pvalue2)
#> [1] TRUE
由reprex package (v0.3.0) 于 2020 年 4 月 23 日创建