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

R中apply函数处理多数据源报错,求批量生成目标结果方案

问题分析与解决方法

核心错误原因

  1. 输入列表创建错误:原代码中input_test = as.data.frame(input_obj)存在拼写错误(input_obj应为input_objects),且将多个数据框转成单个data.frame的方式完全错误——这会把每个input数据框当成新data.frame的一列,而非保留各自的结构。
  2. apply函数误用:apply会将输入转换为矩阵处理,导致传递给result函数的是向量而非数据框,触发「不同来源」错误。批量处理多个数据框应使用专门处理列表的lapply或purrr::map。

修正后的完整代码

library(dplyr)
library(tidyr)

## Inputs ##
input_1 = structure(list(V1 = c("Team_2022", "Team_2022", "Team_2022"), V2 = c("Frank", "Mary", "John"), V3 = c("Sydney", "Sydney", "Sydney"), V4 = c(55, 76, 14)), row.names = c(NA, -3L), class = c("data.table", "data.frame"))
input_2 = structure(list(V1 = c("Team_2023", "Team_2023", "Team_2023"), V2 = c("Bill", "Mary", "John"), V3 = c("Sydney", "Sydney", "Sydney"), V4 = c(113, 23, 10)), row.names = c(NA, -3L), class = c("data.table", "data.frame"))
input_3 = structure(list(V1 = c("Team_2024", "Team_2024", "Team_2024"), V2 = c("Frank", "Mary", "Bill"), V3 = c("Sydney", "Sydney", "Sydney"), V4 = c(7, 19, 52)), row.names = c(NA, -3L), class = c("data.table", "data.frame"))
input_4 = structure(list(V1 = c("Team_2025", "Team_2025", "Team_2025"), V2 = c("Frank", "Mary", "John"), V3 = c("Sydney", "Sydney", "Sydney"), V4 = c(46, 44, 88)), row.names = c(NA, -3L), class = c("data.table", "data.frame"))

## Teams ##
teams = structure(list(V1 = c("team1", "team2", "team3"), V2 = c("Mary + Frank","Mary + John", "Mary + Bill")), class = "data.frame", row.names = c(NA, -3L))

## 正确创建输入列表:收集所有input开头的对象为列表 ##
all_objects = ls()
input_objects = grep("^input", all_objects, value = T)
input_list <- mget(input_objects)

## 修正函数中的转义管道符(原%&gt;%为HTML转义,替换为标准%>%) ##
result = function(input, teams) {
  data = teams %>%
    separate_rows(V2) %>%
    left_join(input, by = c("V2" = "V2")) %>%
    replace_na(list(V4 = 0)) %>%
    group_by(V1.x) %>% 
    fill(V1.y, V3) %>%
    summarize(V1.y = first(V1.y),
              V2 = paste(V2, collapse = " + "),
              V3 = first(V3),
              V4 = sum(V4))
  return(data)
}

## 批量处理并合并结果 ##
output_apply <- lapply(input_list, function(x) result(x, teams)) %>%
  bind_rows()

## 验证结果与预期一致 ##
identical(output_apply, output_desired)

关键说明

  • mget(input_objects):将全局环境中所有匹配input_*的对象收集为列表,每个元素保留完整的data.frame/data.table结构。
  • lapply:遍历列表中的每个数据框,调用result函数处理,避免了apply的矩阵转换问题。
  • bind_rows():比do.call("rbind", .)更兼容不同结构的输出,合并结果更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:15:34