首页 > 解决方案 > 避免在 purrr 映射调用中返回匿名函数中最后评估的表达式

问题描述

考虑一下:

library(tidyverse)

mtcars %>%
  select(mpg, cyl) %>%
  map(
    function(x) {
      cat("*****HEAD******\n")
      print(head(x))
      cat("*****TAIL******\n")
      print(tail(x))
    }
  )

返回:

*****HEAD******
[1] 21.0 21.0 22.8 21.4 18.7 18.1
*****TAIL******
[1] 26.0 30.4 15.8 19.7 15.0 21.4
*****HEAD******
[1] 6 6 4 6 8 6
*****TAIL******
[1] 4 4 8 6 8 4
$`mpg`
[1] 26.0 30.4 15.8 19.7 15.0 21.4

$cyl
[1] 4 4 8 6 8 4

如何避免返回最后评估的表达式(即tail(x))?我想要的输出是:

*****HEAD******
[1] 21.0 21.0 22.8 21.4 18.7 18.1
*****TAIL******
[1] 26.0 30.4 15.8 19.7 15.0 21.4
*****HEAD******
[1] 6 6 4 6 8 6
*****TAIL******
[1] 4 4 8 6 8 4

我尝试过return(NULL)return(NA)return(invisible(x))没有成功。

标签: ranonymous-functionpurrr

解决方案


使用walk()代替map()

capture <- mtcars %>%
  select(mpg, cyl) %>%
  walk(
    function(x) {
      cat("*****HEAD******\n")
      print(head(x))
      cat("*****TAIL******\n")
      print(tail(x))
    }
  )
# *****HEAD******
#   [1] 21.0 21.0 22.8 21.4 18.7 18.1
# *****TAIL******
#   [1] 26.0 30.4 15.8 19.7 15.0 21.4
# *****HEAD******
#   [1] 6 6 4 6 8 6
# *****TAIL******
#   [1] 4 4 8 6 8 4

推荐阅读