Created
July 3, 2023 09:38
-
-
Save avallecam/53a41aaa1d56f8736ba503b9c8e10d01 to your computer and use it in GitHub Desktop.
get confidence intervals from numerator and denominator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` r | |
library(tidyverse) | |
#> Warning: package 'tidyverse' was built under R version 4.2.3 | |
#> Warning: package 'ggplot2' was built under R version 4.2.3 | |
#> Warning: package 'tibble' was built under R version 4.2.3 | |
#> Warning: package 'forcats' was built under R version 4.2.3 | |
# library(datapasta) | |
# tribble_paste() | |
dat <- tibble::tribble( | |
~raw_num, ~raw_den, | |
50L, 141L, | |
55L, 141L, | |
61L, 141L, | |
41L, 141L, | |
53L, 141L, | |
52L, 141L, | |
7L, 141L, | |
5L, 141L | |
) | |
dat | |
#> # A tibble: 8 × 2 | |
#> raw_num raw_den | |
#> <int> <int> | |
#> 1 50 141 | |
#> 2 55 141 | |
#> 3 61 141 | |
#> 4 41 141 | |
#> 5 53 141 | |
#> 6 52 141 | |
#> 7 7 141 | |
#> 8 5 141 | |
dat_out01 <- dat %>% | |
mutate(raw=pmap(.l = select(., x=raw_num,n=raw_den), | |
.f = binom.test)) %>% | |
mutate(raw=map(.x = raw,.f = broom::tidy)) %>% | |
unnest(raw) %>% | |
select(raw_num,raw_den,estimate,starts_with("conf")) | |
dat_out01 | |
#> # A tibble: 8 × 5 | |
#> raw_num raw_den estimate conf.low conf.high | |
#> <int> <int> <dbl> <dbl> <dbl> | |
#> 1 50 141 0.355 0.276 0.440 | |
#> 2 55 141 0.390 0.309 0.476 | |
#> 3 61 141 0.433 0.350 0.519 | |
#> 4 41 141 0.291 0.217 0.373 | |
#> 5 53 141 0.376 0.296 0.461 | |
#> 6 52 141 0.369 0.289 0.454 | |
#> 7 7 141 0.0496 0.0202 0.0996 | |
#> 8 5 141 0.0355 0.0116 0.0808 | |
dat_out02 <- dat_out01 %>% | |
mutate(estimate = estimate *100, | |
conf.low = conf.low * 100, | |
conf.high = conf.high * 100) %>% | |
mutate(estimate = format(estimate, digits = 2), | |
conf.low = format(conf.low, digits = 2), | |
conf.high = format(conf.high, digits = 2)) %>% | |
mutate(conf.all = str_c(conf.low," - ", conf.high)) | |
dat_out02 | |
#> # A tibble: 8 × 6 | |
#> raw_num raw_den estimate conf.low conf.high conf.all | |
#> <int> <int> <chr> <chr> <chr> <chr> | |
#> 1 50 141 "35.5" "27.6" "44.0" "27.6 - 44.0" | |
#> 2 55 141 "39.0" "30.9" "47.6" "30.9 - 47.6" | |
#> 3 61 141 "43.3" "35.0" "51.9" "35.0 - 51.9" | |
#> 4 41 141 "29.1" "21.7" "37.3" "21.7 - 37.3" | |
#> 5 53 141 "37.6" "29.6" "46.1" "29.6 - 46.1" | |
#> 6 52 141 "36.9" "28.9" "45.4" "28.9 - 45.4" | |
#> 7 7 141 " 5.0" " 2.0" "10.0" " 2.0 - 10.0" | |
#> 8 5 141 " 3.5" " 1.2" " 8.1" " 1.2 - 8.1" | |
``` | |
<sup>Created on 2023-07-03 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment