How to add the results of applying a function to an existing data frame?

前端 未结 1 1813
后悔当初
后悔当初 2021-01-25 05:05

I am trying to calculate the confidence intervals of some rates. I am using tidyverse and epitools to calculate CI from Byar\'s method.

I am almost certainly doing somet

相关标签:
1条回答
  • 2021-01-25 05:23

    It's not clear to me what your expected output is supposed to me. Your comment does not really help. Best to explicitly include your expected output for the sample data you give.

    The issue here is that pois.byvar returns a data.frame. So in order for mutate to be able to use the output of pois.byvar we need to store the data.frames in a list.

    Here is a tidier version of your code

    library(tidyverse)
    DATA %>%
        mutate(POPN = case_when(
            AREA == "A" ~ 2.5,
            AREA == "B" ~ 3,
            AREA == "C" ~ 7,
            TRUE ~ 0)) %>%
        group_by(DISEASE,AREA,POPN) %>%
        count(AREA) %>%
        mutate(res = list(pois.byar(n, POPN)))
    

    This creates a column res which contains the data.frame output of pois.byar.

    Or perhaps you'd like to unnest the list column to expand entries into different columns?

    library(tidyverse)
    DATA %>%
        mutate(POPN = case_when(
            AREA == "A" ~ 2.5,
            AREA == "B" ~ 3,
            AREA == "C" ~ 7,
            TRUE ~ 0)) %>%
        group_by(DISEASE,AREA,POPN) %>%
        count(AREA) %>%
        mutate(res = list(pois.byar(n, POPN))) %>%
        unnest()
    ## A tibble: 9 x 10
    ## Groups:   DISEASE, AREA, POPN [9]
    #  DISEASE     AREA   POPN     n     x    pt  rate  lower upper conf.level
    #  <fct>       <fct> <dbl> <int> <int> <dbl> <dbl>  <dbl> <dbl>      <dbl>
    #1 Chicky Pox  A       2.5     1     1   2.5 0.4   0.0363 1.86        0.95
    #2 Chicky Pox  B       3       2     2   3   0.667 0.133  2.14        0.95
    #3 Chicky Pox  C       7       2     2   7   0.286 0.0570 0.916       0.95
    #4 Marco Polio A       2.5     2     2   2.5 0.8   0.160  2.56        0.95
    #5 Marco Polio B       3       2     2   3   0.667 0.133  2.14        0.95
    #6 Marco Polio C       7       1     1   7   0.143 0.0130 0.666       0.95
    #7 Mumps       A       2.5     2     2   2.5 0.8   0.160  2.56        0.95
    #8 Mumps       B       3       1     1   3   0.333 0.0302 1.55        0.95
    #9 Mumps       C       7       2     2   7   0.286 0.0570 0.916       0.95
    
    0 讨论(0)
提交回复
热议问题