For each row in a tibble, a function call to quantile()
will generate multiple values. How can I put each in a different column?
I've tried putting the whole set in a temporary column, but that doesn't seem to work.
tibble(category = LETTERS[1:10]) %>%
rowwise() %>%
# put everything in a temporary "range" column
mutate(range = quantile(rnorm(count), c(0.025, 0.975), names = FALSE) ) %>%
# put each value in a column
mutate(lo = range[[1]], hi = range[[2]]) %>%
ungroup() %>%
select(-range)
you can use an approach which relies on purrr::map
. For each row you compute the quantiles and save the results into a tibble using ´enframe`. Then you unnest the result:
library(tidyverse)
df <- tibble(count = c(100, 1000, 10000))
set.seed(1)
df %>%
mutate(q = map(count, ~quantile(rnorm(.x), c(0.025, 0.975)) %>%
enframe %>%
spread(name, value))) %>%
unnest(q)
# A tibble: 3 x 3
count `2.5%` `97.5%`
<dbl> <dbl> <dbl>
1 100 -1.67 1.80
2 1000 -2.13 2.01
3 10000 -1.99 1.97
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.