在mutate()之外以行方式使用purrr :: pmap()

时间:2018-11-20 23:27:35

标签: r purrr pmap

我正在尝试使用purrr :: pmap()沿某些数据帧行以行方式应用自定义函数。我可以使用for循环和apply()来达到期望的最终结果,但是当我尝试使用pmap()时,我只能将我想要的结果与mutate()结合使用,寿命的情况将不足。

有没有一种方法可以使用pmap()来应用我的自定义函数,并且仅输出输出而不是存储在新列中?

library(dplyr)
library(purrr)
library(tibble)

创建演示数据和自定义功能

set.seed(57)

ds_mt <- 
  mtcars %>% 
    rownames_to_column("model") %>% 
    mutate(
      am = factor(am, labels = c("auto", "manual")), 
      vs = factor(vs, labels = c("V", "S"))
    ) %>% 
  select(model, mpg, wt, cyl, am, vs) %>% 
  sample_n(3)

foo <- function(model, am, mpg){
  print(
    paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
  )
}

逐行for循环的成功示例:

for (row in 1:nrow(ds_mt)) {
  foo(
    model = ds_mt[row, "model"], 
    am    = ds_mt[row, "am"],
    mpg   = ds_mt[row, "mpg"]
  )
}

使用apply()的成功示例:

row.names(ds_mt) <- NULL # to avoid named vector as output

  apply(
    ds_mt, 
    MARGIN = 1, 
    FUN = function(ds) 
      foo(
        model = ds["model"],
        am = ds["am"],
        mpg = ds["mpg"]
      )
  ) 

pmap()中使用mutate()的示例几乎是我所需要的。

ds_mt %>% 
  mutate(new_var = 
    pmap(
      .l = 
        list(
          model = model,
          am = am,
          mpg = mpg
        ),
      .f = foo
    ))

失败代码:为什么这行不通?

ds_mt %>% 
  pmap(
    .l = 
      list(
        model = model,
        am = am,
        mpg = mpg
      ),
    .f = foo
  )

1 个答案:

答案 0 :(得分:1)

因此,经过更多阅读后,看来pwalk()而不是pmap()属于这种情况,因为我试图将输出打印(即副作用)而不是存储在其中一个数据框。

library(dplyr)
library(purrr)
library(tibble)

set.seed(57)

ds_mt <- 
  mtcars %>% 
  rownames_to_column("model") %>% 
  mutate(
    am = factor(am, labels = c("auto", "manual")), 
    vs = factor(vs, labels = c("V", "S"))
  ) %>% 
  select(model, mpg, wt, cyl, am, vs) %>% 
  sample_n(3)

foo <- function(model, am, mpg){
  print(
    paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
  )
}

ds_mt %>% 
  select(model, am, mpg) %>% 
  pwalk(
  .l = .,
  .f = foo
)