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

如何在R语言营养评分计算器函数中指定参考查找表?

营养评分计算器函数实现方案

问题背景

需要实现一个营养评分计算器,输入食物的纤维含量和食物类别,根据对应类别的评分规则输出健康评分。已完成产品类别映射表和两类评分规则表的定义,函数已能根据食物获取对应的类别,但不知道如何根据类别动态选择评分表并匹配分数。

现有基础代码:

library(tidyverse)

product_category <- tibble(
  food_type = c("Fruits", "Vegetables"),
  category = c("Category A", "Category B")
)

score_schedule_a <- tibble(
  fibre_amount = c(1, 2, 3),
  score = c(3, 6, 9)
)

score_schedule_b <- tibble(
  fibre_amount = c(1, 2, 3),
  score = c(6, 12, 18)
)

已完成的函数开头:

score_calculator <- function(fibre, food) {
  category <- product_category %>%
    filter(food_type == food) %>%
    pull(category)
}

预期效果:

  • score_calculator(2, "Vegetables") 输出 12
  • score_calculator(1, "Vegetables") 输出 6
  • score_calculator(1, "Fruits") 输出 3

解决方案

核心思路是将评分表与类别名称关联,通过类别直接索引到对应的评分表,再匹配纤维值获取分数。

步骤1:将评分表存入命名列表

把两个评分表放到一个命名列表中,列表的键对应product_category中的类别名称,这样可以通过类别字符串直接获取对应表:

# 用命名列表关联类别和评分表
score_schedules <- list(
  "Category A" = score_schedule_a,
  "Category B" = score_schedule_b
)

步骤2:完善评分函数

在函数中,通过获取到的category从列表中取出对应评分表,再筛选匹配的纤维值并提取分数:

score_calculator <- function(fibre, food) {
  # 获取食物对应的类别
  category <- product_category %>%
    filter(food_type == food) %>%
    pull(category)
  
  # 根据类别获取对应的评分规则表
  selected_schedule <- score_schedules[[category]]
  
  # 匹配纤维值并返回对应评分
  selected_schedule %>%
    filter(fibre_amount == fibre) %>%
    pull(score)
}

测试验证

运行以下测试代码,结果符合预期:

score_calculator(2, "Vegetables") # [1] 12
score_calculator(1, "Vegetables") # [1] 6
score_calculator(1, "Fruits")     # [1] 3

可选优化(处理异常情况)

如果输入的纤维值不在评分表范围内,可以添加默认处理逻辑,比如返回NA并给出提示:

score_calculator <- function(fibre, food) {
  category <- product_category %>%
    filter(food_type == food) %>%
    pull(category)
  
  selected_schedule <- score_schedules[[category]]
  
  result <- selected_schedule %>%
    filter(fibre_amount == fibre) %>%
    pull(score)
  
  if (length(result) == 0) {
    warning("输入的纤维值无对应评分规则")
    return(NA)
  }
  
  result
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:01:18