0

我正在尝试使用 purrr::pmap() 沿某些数据帧行以逐行方式应用自定义函数。我可以使用 for 循环和 with 实现我想要的最终结果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
  )
4

1 回答 1

2

因此,在阅读了更多内容之后,这似乎是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
)
于 2018-11-27T00:22:52.517 回答