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

marginaleffects包predictions函数返回closure错误求助

问题解决思路

报错根源

  1. datagrid参数语法变更:旧版本marginaleffects允许用hour = unique简写提取变量唯一值,但新版本(0.5.0)不再支持这种写法,unique作为R内置函数(closure类型)被传入后,无法被强制转换为字符向量,触发类型错误。
  2. sprintf参数顺序错误:原代码中sprintf(estimate, fmt = '%#.1f')的参数顺序颠倒,sprintf要求格式字符串作为第一个参数,数值作为第二个参数,这会导致格式化失败。

修正方案

方案1:利用datagrid的model参数自动生成新数据

datagrid的model参数可以自动从模型中提取变量,并使用其典型取值(因子变量会自动取所有水平),无需手动指定变量取值:

require(nycflights13)
require(dplyr)
require(marginaleffects)
require(tibble)

bA <- lm(as.numeric(arr_delay) ~ hour, 
         data = flights %>% 
           filter(month == 4, distance < 900) %>%
           mutate(hour = as.factor(hour))) 

bB <- predictions(bA, newdata = datagrid(model = bA), conf_level = 0.99857) %>%
  as_tibble() %>% 
  arrange(hour) %>%
  mutate(estimate = 
           paste0(sprintf('%#.1f', estimate), " (", 
                  sprintf('%#.1f', conf.low), "; ", 
                  sprintf('%#.1f', conf.high), ")")) %>%
  select(hour, estimate)

方案2:手动传入变量的唯一值向量

直接从模型数据中提取hour的唯一值,传入datagrid:

require(nycflights13)
require(dplyr)
require(marginaleffects)
require(tibble)

bA <- lm(as.numeric(arr_delay) ~ hour, 
         data = flights %>% 
           filter(month == 4, distance < 900) %>%
           mutate(hour = as.factor(hour))) 

bB <- predictions(bA, newdata = datagrid(hour = unique(bA$model$hour)), conf_level = 0.99857) %>%
  as_tibble() %>% 
  arrange(hour) %>%
  mutate(estimate = 
           paste0(sprintf('%#.1f', estimate), " (", 
                  sprintf('%#.1f', conf.low), "; ", 
                  sprintf('%#.1f', conf.high), ")")) %>%
  select(hour, estimate)

验证说明

两种方案都能解决类型错误,同时修正sprintf的参数顺序后,可正确格式化预测值和置信区间为指定格式。

内容的提问来源于stack exchange,提问作者C.Robin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:52:24