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

tidymodels中recipe step_mutate处理NA日期时破坏非NA日期问题

问题原因

基础R自带的ifelse函数会自动丢弃输入的Date类属性,将日期值转换为对应的底层整数时间戳,因此最终输出的date1列变成了数值类型而非预期的日期类型。

解决方法

可以选择以下任意一种方案替换原有逻辑:

  • 方案1:使用dplyr的if_else替代基础ifelse,该函数会严格保留输入数据的类型,不会发生自动强转
    rec <- recipes::recipe(target ~ ., data = df) %>% 
      recipes::step_mutate(date1 = dplyr::if_else(is.na(date1), lubridate::ymd("1900-01-01"), date1)) %>%
      prep() %>% 
      juice()
    
  • 方案2:使用tidyr::replace_na实现NA固定值填充,写法更简洁
    rec <- recipes::recipe(target ~ ., data = df) %>% 
      recipes::step_mutate(date1 = tidyr::replace_na(date1, lubridate::ymd("1900-01-01"))) %>%
      prep() %>% 
      juice()
    
  • 方案3:直接使用recipes自带的常量填充步骤,不需要手动写mutate逻辑
    rec <- recipes::recipe(target ~ ., data = df) %>% 
      recipes::step_impute_const(date1, value = lubridate::ymd("1900-01-01")) %>%
      prep() %>% 
      juice()
    

以上三种方案运行后得到的date1列均为预期的Date类型,值为2020-08-05和1900-01-01。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:24:06