避免在 purrr 映射调用中返回匿名函数中最后计算的表达式

Avoid returning last evaluated expression in anonymous function within purrr map call

考虑一下:

library(tidyverse)

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

哪个returns:

*****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)) 但没有成功。

使用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

只需将 %>% invisible 附加到管道的末尾。它仍然会 return 相同的结果,但会以不可见的方式进行,因此输入它不会显示任何结果。

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

给予:

*****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