gpt4 book ai didi

r - 如何使用 purrr 的 map 函数执行 row-wise prop.tests 并将结果添加到数据帧?

转载 作者:行者123 更新时间:2023-12-02 05:57:05 25 4
gpt4 key购买 nike

我正在尝试解决 R 中的以下问题:我有一个包含两个变量(成功次数和总试验次数)的数据框。

# A tibble: 4 x 2
Success N
<dbl> <dbl>
1 28. 40.
2 12. 40.
3 22. 40.
4 8. 40.

我想对每一行执行 prop.test 或 binom.test 并将结果列表添加到数据帧(或其中的某些元素,如 p 值和 CI)。

理想情况下,我想添加包含 p 值和 CI 范围的第三列。到目前为止,我的尝试都非常失败。这是一个最小的编码示例:
Success <- c( 38, 12, 27, 9)
N <- c( 50, 50, 50, 50)
df <- as.tibble( cbind(Success, N))


df %>%
map( ~ prop.test, x = .$Success, n = .$N)

没有给出想要的结果。任何帮助将非常感激。

干杯,

路易丝

最佳答案

我们可以使用 pmap使用“prop.test”的参数更改列名后

pmap(setNames(df, c("x", "n")), prop.test)

或使用 map2
map2(df$Success, df$N, prop.test)
map 的问题是它循环遍历数据集的每一列,它是一个 listvector
df %>%
map(~ .x)
#$Success
#[1] 38 12 27 9

#$N
#[1] 50 50 50 50
所以,我们不能做 .x$Success.x$N更新
正如@Steven Beaupre 提到的,如果我们需要创建具有 p 值和置信区间的新列
res <- df %>%
mutate(newcol = map2(Success, N, prop.test),
pval = map_dbl(newcol, ~ .x[["p.value"]]),
CI = map(newcol, ~ as.numeric(.x[["conf.int"]]))) %>%
select(-newcol)
# A tibble: 4 x 4
# Success N pval CI
# <dbl> <dbl> <dbl> <list>
#1 38.0 50.0 0.000407 <dbl [2]>
#2 12.0 50.0 0.000407 <dbl [2]>
#3 27.0 50.0 0.671 <dbl [2]>
#4 9.00 50.0 0.0000116 <dbl [2]>
“CI”列是 list 2 个元素,可以是 unnest ed 使其成为“长”格式数据
res %>%
unnest

或创建 3 列
df %>% 
mutate(newcol = map2(Success, N, ~ prop.test(.x, n = .y) %>%
{tibble(pvalue = .[["p.value"]],
CI_lower = .[["conf.int"]][[1]],
CI_upper = .[["conf.int"]][[2]])})) %>%
unnest
# A tibble: 4 x 5
# Success N pvalue CI_lower CI_upper
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 38.0 50.0 0.000407 0.615 0.865
#2 12.0 50.0 0.000407 0.135 0.385
#3 27.0 50.0 0.671 0.395 0.679
#4 9.00 50.0 0.0000116 0.0905 0.319

关于r - 如何使用 purrr 的 map 函数执行 row-wise prop.tests 并将结果添加到数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com