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

允我心安 提交于 2019-12-02 05:53:22

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!