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

前端 未结 4 2284
攒了一身酷
攒了一身酷 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:59

    With pmap, the first argument is a list, so you can pass it your data frame directly, and then name your arguments in your function with the same names as the columns in your data frame. You'll need unnest() to unpack the list elements returned by pmap():

    df.preprocessed <- dplyr::as.tbl(params) %>%
        dplyr::mutate(test_var = purrr::pmap(., function(param_a, param_b, ...){
                                            rep(5, param_a) * param_b
                                         })) %>%
        tidyr::unnest()
    
    
    > df.preprocessed
    # A tibble: 144 x 5
       param_a param_b param_c param_d test_var
                      
     1       2       3      50       1       15
     2       2       3      50       1       15
     3       4       3      50       1       15
     4       4       3      50       1       15
     5       4       3      50       1       15
     6       4       3      50       1       15
     7       6       3      50       1       15
     8       6       3      50       1       15
     9       6       3      50       1       15
    10       6       3      50       1       15
    # ... with 134 more rows
    

提交回复
热议问题