我想vectorize 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)
先谢谢你了,
4条答案
按热度按时间b4qexyjb1#
使用
base R
tmb3ates2#
输出:
3ks5zfa03#
我终于找到了解决办法:
bq9c1y664#
使用
group_split
和map_dfr
的一种方法:输出: