Q:

Using poisson.test with dplyr

I want to run a Poisson test on every row of a tibble. However, mutate fails because poisson.test seems to be designed for numbers rather than columns. What is the best workaround? At the moment, the only thing I've managed to get working is an explicit for loop...
df <- tribble(
~count, ~time,
5, 10,
4, 7,
8, 10)

# Fails
df %>% mutate(rate = poisson.test(count, T = time)
# Error in poisson.test(remove_count, T = FHs) : 
#   the case k > 2 is unimplemented

A:

As we want to apply on each row, one option is map2 where it takes each element of 'count', 'time' and do the poisson.test
library(dplyr)
library(purrr)
df %>%
   mutate(rate = map2(count, time, poisson.test))

Or if we don't want to load another package (purrr), then this can be done with rowwise
df %>% 
   rowwise %>%
   mutate(rate = list(poisson.test(count, time))) 

This will give the test output as a list column.  If we are interested in extracting the estimate
df %>%
   mutate(rate = map2_dbl(count, time, ~poisson.test(.x, .y)$estimate))
# A tibble: 3 x 3
#  count  time  rate
#  <dbl> <dbl> <dbl>
#1     5    10 0.5  
#2     4     7 0.571
#3     8    10 0.8  

