繁体   English   中英

如何使用purrr的map函数执行逐行的prop.test并将结果添加到数据框?

[英]How to use purrr's map function to perform row-wise prop.tests and add results to the dataframe?

我正在尝试解决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)

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

干杯,

路易丝

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

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

或使用map2

map2(df$Success, df$N, prop.test)

map的问题在于它遍历数据集的每一列,并且是vector s的list

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”列是2个元素的list ,可以将其unnest以使其成为“长”格式数据

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

如果你想要一个新的专栏,你会使用@ akrun的做法,但在一个小洒dplyrbroom跻身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将函数应用到嵌套框架,然后使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM