Using purrr::pmap within mutate to create list-column

前端 未结 4 2286
攒了一身酷
攒了一身酷 2021-01-04 08:20

I understand how to use map to iterate over arguments in a df and create a new list column.

For example,

params <- expand.grid(param_a = c(2, 4,          


        
4条回答
  •  粉色の甜心
    2021-01-04 08:54

    You can do this:

    df.preprocessed <- dplyr::as.tbl(params) %>%
      dplyr::mutate(test_var = purrr::pmap(list(x = param_a
                                                ,y = param_b
                                                ,z = param_c
                                                ,u = param_d),
                                                  ~ rep(5,.x)*.y                                                
      )
      )
    

    or

    df.preprocessed <- dplyr::as.tbl(params) %>%
      dplyr::mutate(test_var = purrr::pmap(list(x = param_a
                                                ,y = param_b
                                                ,z = param_c
                                                ,u = param_d),
                                           ~ rep(5,..1)*..2                                       
      )
      )
    

    The second way is more general as you can use ..3, ..4 etc...

提交回复
热议问题