r - 避免在 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))
没有成功。
解决方案
使用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
推荐阅读
- python - 阻止 Tensorflow 根据请求重新加载模型
- windows - 什么是压缩 GUID,为什么要使用它?
- javascript - 实现格路径计数的递归
- javascript - 如何在javascript中的变量中定义变量
- javascript - 如何向 Angular 应用程序发出 CORS HTTP 请求
- android - 代理设置不适用于 Chrome Webview
- c# - ASP.NET 设置用户身份和 IsAuthenticated = true
- azure-ad-b2c - 更新 Azure B2C 自定义策略中的显示名称
- sinch - Android Sinch PubNubListener:6 次尝试后永久订阅失败
- c# - PlaceHolder 重复按钮单击插入错误太多参数