You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化purrr::safely()与purrr::map()输出并转为数据框?

将purrr::map结合safely的运行结果转换为数据框

可以通过purrr和tibble包的工具快速将safely返回的嵌套列表转换为目标数据框,以下是具体实现:

原代码(含中文注释)

# 定义目标函数:计算数据框行数+列数的和,行数超过149时抛出错误
sum_of_dimensions <- function(df){
  stopifnot(nrow(df) < 150)
  result <- nrow(df) + ncol(df)
  return(result)
}

# 创建待处理的数据框列表
dfs <- list(mtcars = mtcars, iris = iris)

# 使用safely包装函数后执行映射
list_safe <- 
  purrr::map(
    dfs,
    purrr::safely(sum_of_dimensions)
  )

转换为数据框的方法

方法1:使用map_dfr快速转换

利用map_dfr直接将嵌套列表行绑定为数据框,同时通过.id参数保留原列表的元素名称:

library(tibble)
library(purrr)

result_df <- map_dfr(list_safe, ~as_tibble(.x), .id = "item")

# 查看结果
result_df

输出结果:

# A tibble: 2 × 3
  item   result error     
  <chr>  <list> <list>    
1 mtcars <int [1]>  <NULL>    
2 iris   <NULL> <simpleError: nrow(df) < 150 is not TRUE>

方法2:手动构建数据框

如果需要更灵活的结构控制,可以手动提取result和error字段构建数据框:

library(tibble)
library(purrr)

result_df <- tibble(
  item = names(list_safe),
  result = map(list_safe, "result"),
  error = map(list_safe, "error")
)

这个方法得到的结果和方法1完全一致,符合你需要的结构:每行对应原列表的一个元素,包含元素名称、结果列表和错误列表。

内容的提问来源于stack exchange,提问作者joshbrows

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:03:13