dplyr::mutate to add multiple values

前端 未结 6 1596
旧时难觅i
旧时难觅i 2020-11-30 04:15

There are a couple of issues about this on the dplyr Github repo already, and at least one related SO question, but none of them quite covers my question -- I think.

6条回答
  •  清歌不尽
    2020-11-30 04:17

    Yet another option could be to use the purrr::map family of functions.

    If you replace rbind with dplyr::bind_rows in the get_binCI function:

    library(tidyverse)
    
    dd <- data.frame(x = c(3, 4), n = c(10, 11))
    get_binCI <- function(x, n) {
      bind_rows(setNames(c(binom.test(x, n)$conf.int), c("lwr", "upr")))
    }
    

    You can use purrr::map2 with tidyr::unnest:

    dd %>% mutate(result = map2(x, n, get_binCI)) %>% unnest()
    
    #>   x  n        lwr       upr
    #> 1 3 10 0.06673951 0.6524529
    #> 2 4 11 0.10926344 0.6920953
    

    Or purrr::map2_dfr with dplyr::bind_cols:

    dd %>% bind_cols(map2_dfr(.$x, .$n, get_binCI))
    
    #>   x  n        lwr       upr
    #> 1 3 10 0.06673951 0.6524529
    #> 2 4 11 0.10926344 0.6920953
    

提交回复
热议问题