我正在尝试计算几个二项式比例置信区间。我的数据位于数据框中,虽然我可以成功地estimate从 返回的对象中提取 ,但在数据框中运行时prop.test该conf.int变量似乎为空。
library(dplyr)
cases <- c(50000, 1000, 10, 2343242)
population <- c(100000000, 500000000, 100000, 200000000)
df <- as.data.frame(cbind(cases, population))
df %>% mutate(rate = prop.test(cases, population, conf.level=0.95)$estimate)
Run Code Online (Sandbox Code Playgroud)
这适当地返回
cases population rate
1 50000 1e+08 0.00050000
2 1000 5e+08 0.00000200
3 10 1e+05 0.00010000
4 2343242 2e+08 0.01171621
Run Code Online (Sandbox Code Playgroud)
然而,当我跑
df %>% mutate(confint.lower= prop.test(cases, pop, conf.level=0.95)$conf.int[1])
Run Code Online (Sandbox Code Playgroud)
我伤心地得到
Error in mutate_impl(.data, dots) :
Column `confint.lower` is of unsupported type NULL
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?我知道计算二项式比例置信区间的替代方法,但我真的很想学习如何使用dplyr。
谢谢!
您可以使用dplyr::rowwise()对行进行分组:
df %>%
rowwise() %>%
mutate(lower_ci = prop.test(cases, pop, conf.level=0.95)$conf.int[1])
Run Code Online (Sandbox Code Playgroud)
默认情况下dplyr采用列名并将它们视为向量。所以矢量化函数,比如上面提到的@Jake Fisher,不需要rowwise()添加。
这是我一次捕获所有置信区间组件的方法:
df %>%
rowwise %>%
mutate(tst = list(broom::tidy(prop.test(cases, pop, conf.level=0.95)))) %>%
tidyr::unnest(tst)
Run Code Online (Sandbox Code Playgroud)