【问题标题】:Using poisson.test with dplyr将 poisson.test 与 dplyr 一起使用
【发布时间】:2019-10-10 18:00:15
【问题描述】:

我想对 tibble 的每一行进行泊松检验。但是, mutate 失败了,因为 poisson.test 似乎是为数字而不是列设计的。最好的解决方法是什么?目前,我唯一设法开始工作的是一个明确的 for 循环......

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

【问题讨论】:

    标签: r dplyr statistics


    【解决方案1】:

    由于我们想在每一行上应用,一个选项是map2,它采用'count'、'time'的每个元素并执行poisson.test

    library(dplyr)
    library(purrr)
    df %>%
       mutate(rate = map2(count, time, poisson.test))
    

    或者如果我们不想加载另一个包 (purrr),那么可以使用 rowwise 来完成

    df %>% 
       rowwise %>%
       mutate(rate = list(poisson.test(count, time))) 
    

    这会将测试输出作为list 列。如果我们有兴趣提取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  
    

    【讨论】:

    • 谢谢!简单的问题。如果我使用df2 = df %&gt;% mutate(rate = map2(count, time, poisson.test)),我将如何从列表列中提取多个元素(例如估计和置信区间)?
    • @yakzo 你可以做df2 %&gt;% mutate(est = map_dbl(rate, ~ .x$estimate), confL = map_dbl(rate, ~ .x$conf.int[1]), confU = map_dbl(rate, ~ .x$conf.int[2]))
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2021-09-07
    • 2017-12-29
    • 2015-03-16
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多