我想要将 fisher.test 函数向量化,以便可以并行应用于多个变量。
例如: 构建一个玩具数据集。
例如: 构建一个玩具数据集。
library(tidyverse)
library(broom)
n=20
outcome <- rbinom(n, size =c(0,1), prob = 0.7)
feature1 <- rbinom(n, size=c(2), prob = 0.5) + 10
feature2 <- rbinom(n, size=c(1), prob = 0.5)+20
df <- tibble(outcome, feature1, feature2)
这是一个功能的预期输出:
df %>%
select(outcome, feature1) %>%
count(outcome, feature1) %>%
pivot_wider(names_from = feature1, values_from = n) %>%
fisher.test(.) %>%
tidy()
我尝试了group_modify,并尝试将其并行应用于几个不同的变量,但它不起作用:
df %>%
pivot_longer(c("feature1", "feature2"), names_to = "variable", values_to = "value") %>%
group_by(variable) %>%
group_modify(~count(outcome, value)) %>%
pivot_wider(names_from = value, values_from = n) %>%
fisher.test(.) %>%
tidy()
我得到错误信息 "no method 'count' applicable for an object of class c("integer', 'numeric')"
理想情况下,我的最终输出应该是:
all_pvalues <- tribble(
~variable, ~p.value,
feature1, 0.805,
feature2, 0.582)
非常感谢您的提前帮助,