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

R如何按单列分组后将另一列转为向量并传入自定义函数计算

R语言分组生成列表列并调用自定义函数实现方案

需求说明

  • 示例数据框如下:
person <- c("a","a","a","b","b","b","c","c","c")
score <- c(31,2,13,5,6,7,8,9,4)
df <- data.frame(person,score)
  • 需要得到3行2列的结构,每行对应唯一person值,以及该person对应的所有score组成的向量
  • 最终要将每组的score向量传入自定义函数计算,自定义函数要求传入两个等长向量,其中一个为固定预定义向量

实现代码

基于dplyr实现(推荐)

你原有代码不生效的原因是summarise默认会把返回的多元素向量拆分为多行,只需要将结果用list()包裹生成为列表列即可:

library(dplyr)
# 自定义函数
f <- function(x,y){x-y}

# 直接生成分组计算结果
result <- df %>% 
  group_by(person) %>% 
  summarise(
    # 存储每组的score向量为列表元素,不需要可省略该行
    score_vec = list(score),
    # 自定义函数返回结果也存为列表元素
    diff_result = list(f(c(1,2,3), score))
  )

基于base R实现

不需要依赖第三方包的实现方式:

# 自定义函数
f <- function(x,y){x-y}
# 按person分组生成向量列表
group_score <- split(df$score, df$person)
# 批量调用自定义函数
calc_result <- lapply(group_score, function(y) f(c(1,2,3), y))
# 转为3行2列数据框
result <- data.frame(
  person = names(group_score),
  score_vec = I(unname(group_score)),
  diff_result = I(unname(calc_result))
)

结果验证

# 查看person为a对应的score向量
result$score_vec[result$person == "a"]
# 输出:31 2 13
# 查看person为a对应的计算结果
result$diff_result[result$person == "a"]
# 输出:-30  0 -10,对应1-31、2-2、3-13的计算结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:18:03