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

后端 未结 2 745
囚心锁ツ
囚心锁ツ 2021-01-03 11:24

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
          


        
2条回答
  •  梦谈多话
    2021-01-03 11:59

    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)) 
    

    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
                     
    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
    

提交回复
热议问题