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

如何让R函数返回含lda模型、数据框和ggplot的命名列表?

问题:R函数无法返回带命名元素的列表

编写R函数时,没法让函数返回包含多个元素的命名列表,试了好几种方法都不行,查了Stack Overflow相关问题也没解决,怀疑是代码存在拼写错误。

期望返回的列表元素

  • Linear判别分析模型(lda)
  • 一个dataframe
  • 一张ggplot图像

当前使用的函数版本

fun <- function(data, tooth_type = c("m1", "m2", "m3"), position = c("U", "L")) {
  model <- lda(Species ~ MD + BL, data = data) 
  # 从Omo数据库提取目标牙齿信息
  tooth <- omo_numeric_mdbl[omo_numeric_mdbl$Tooth == tooth_type & omo_numeric_mdbl$Position == position, ]
  tooth <- tooth[complete.cases(tooth[, 31:32]), ]
  predictions <- model %>%
    predict(tooth)
  pred <- as.data.frame(predictions$posterior)*100
  # 绘图
  lda.data <- cbind(data, predict(model)$x)
  ggplot_fun <- ggplot(lda.data, aes(LD1, LD2)) +
    geom_point(aes(color = Species))
  list(model, pred, ggplot_fun)
}

函数内需要存储的三个对象

  • pred:目标dataframe
  • model:lda模型信息
  • ggplot_fun:ggplot图像

已尝试的方法(均未成功)

  • as.list(model, pred, ggplot_fun)
  • list(model, pred, ggplot_fun)
  • x <- as.list(model, pred, ggplot_fun); return(x)
  • x <- list(model, pred, ggplot_fun); return(x)

最终期望的调用效果

x <- fun(data, "m3", "L") # 示例调用

x$pred       # 查看dataframe(可按需用kable展示)
x$model      # 查看lda模型,可通过x$model$posterior获取内部细节
x$ggplot_fun # 展示ggplot图像

解决方案

问题核心是你返回的列表没有给元素命名,所以无法通过$元素名的方式访问。只需要在创建列表时为每个元素指定名字即可。

修改后的函数关键行:
将原代码中的list(model, pred, ggplot_fun)替换为:

list(model = model, pred = pred, ggplot_fun = ggplot_fun)

修改后的完整函数

fun <- function(data, tooth_type = c("m1", "m2", "m3"), position = c("U", "L")) {
  model <- lda(Species ~ MD + BL, data = data) 
  # 从Omo数据库提取目标牙齿信息
  tooth <- omo_numeric_mdbl[omo_numeric_mdbl$Tooth == tooth_type & omo_numeric_mdbl$Position == position, ]
  tooth <- tooth[complete.cases(tooth[, 31:32]), ]
  predictions <- model %>%
    predict(tooth)
  pred <- as.data.frame(predictions$posterior)*100
  # 绘图
  lda.data <- cbind(data, predict(model)$x)
  ggplot_fun <- ggplot(lda.data, aes(LD1, LD2)) +
    geom_point(aes(color = Species))
  # 给列表元素命名
  list(model = model, pred = pred, ggplot_fun = ggplot_fun)
}

这样调用函数后,就能通过x$model、x$pred、x$ggplot_fun分别访问对应的元素了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:25:21