如何使用purrr的map函数执行逐行的prop.test并将结果添加到数据框? [英] How to use purrr's map function to perform row-wise prop.tests and add results to the dataframe?
问题描述
我正在尝试解决R中的以下问题:我有一个包含两个变量(成功次数和总试验次数)的数据框。
I'm trying to solve the following problem in R: I have a dataframe with two variables (number of successes, and number of total trials).
# 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-
I would like to perform a prop.test or binom.test on each row and add the resulting list to the dataframe (or certain elements of it, like the p-value and CIs).
理想情况下,我想添加第三列,其中包含p值和CI范围。到目前为止,我的尝试都没有成功。这是一个最小的编码示例:
Ideally, I would like to add a third column with the p-values and the CI-range. My attempts so far were painly unsuccessful. Here is a minimal coding example:
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)
没有给出期望的结果。
Doesn't give the desired result. Any help would be much appreciated.
干杯,
Luise
推荐答案
如果您想要一个新列,可以使用@akrun的方法,但要撒一些 dplyr
和扫帚
在 purrr
If you want a new column, you'd use @akrun's approach but sprinkle in a little dplyr
and broom
amongst the purrr
library(tidyverse) # for dplyr, purrr, tidyr & co.
library(broom)
analysis <- df %>%
set_names(c("x","n")) %>%
mutate(result = pmap(., prop.test)) %>%
mutate(result = map(result, tidy))
从那里开始,您可以得到整齐的嵌套小标题的结果。如果您只想将其限制为某些变量,只需遵循 mutate
/ map
将函数应用于
From there that gives you the results in a tidy nested tibble. If you want to just limit that to certain variables, you'd just follow the mutate
/map
applying functions to the nested frame, then unnest().
analysis %>%
mutate(result = map(result, ~select(.x, p.value, conf.low, conf.high))) %>%
unnest()
# A tibble: 4 x 5
x n p.value conf.low conf.high
<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
这篇关于如何使用purrr的map函数执行逐行的prop.test并将结果添加到数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!