【问题标题】:purrr::pmap with dplyr::mutatepurrr::pmap 与 dplyr::mutate
【发布时间】:2018-04-07 08:31:39
【问题描述】:

我有一个函数,它接受多个输入并创建多个输出。例如:

example_fun = function(a,b){
    x = a+b
    y = a-b
    return(list(x=x, y=y))
}

如何使用 dplyr::mutate 在数据帧的每一行上评估此函数?转

df = expand.grid(a=c(7,8), b=c(9,10))

df
  a  b
1 7  9
2 8  9
3 7 10
4 8 10

进入

  a  b  x  y
1 7  9 16 -2
2 8  9 17 -1
3 7 10 17 -3
4 8 10 18 -2

以下代码几乎完成了它:

df = df %>%
    mutate(outputs = pmap(list(a,b), example_fun)) %>%
    unnest()

df
  a  b outputs
1 7  9      16
2 7  9      -2
3 8  9      17
4 8  9      -1
5 7 10      17
6 7 10      -3
7 8 10      18
8 8 10      -2

【问题讨论】:

    标签: r dplyr tidyverse purrr


    【解决方案1】:

    稍微改变一下:

    example_fun = function(a, b) {
      x = a + b
      y = a - b
      return(data_frame(x = x, y = y)) #data_frame, not list
    }
    
    df <- data_frame(a = sample(1:5, 10, rep = TRUE), b = 11:20) #made my own test dataset
    
    df %>%
      mutate(outputs = map2(a, b, example_fun)) %>% #I use map2 rather than pmap
      unnest()
    

    【讨论】:

      【解决方案2】:

      我们可以使用pmap 中的原始函数执行此操作,方法是应用该函数将输出作为tibble,然后将bind_rows 与原始数据集一起使用

      df %>% 
         pmap_df(example_fun) %>%
         bind_cols(df, .)
      #   a  b  x  y
      #1 7  9 16 -2
      #2 8  9 17 -1
      #3 7 10 17 -3
      #4 8 10 18 -2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        相关资源
        最近更新 更多