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

使用data.table::fcase()替代dplyr::case_when()时如何保留行默认值?

使用data.table::fcase()替代dplyr::case_when()并保留原行值作为默认值的解决方案

问题场景

你尝试用data.table::fcase()替代dplyr::case_when()处理数据,但在设置默认值为原列对应行的值时报错。示例数据如下:

dt <- data.table(v1 = c("1","2", "3", NA))

用dplyr::case_when()可以得到预期结果:

dt %>%
  mutate( v2 = case_when(is.na(v1) ~ "0",
                         TRUE ~ v1))

输出结果:

v1 v2
1:    1  1
2:    2  2
3:    3  3
4: <NA>  0

但使用fcase()时,以下代码会报错:

dt[ , v2 := fcase(is.na(v1), "0",
                  default = v1)]

错误信息:

Error in fcase(is.na(v1), "0", default = v1) : 
  Length of 'default' must be 1.

解决方案

fcase()的default参数仅接受长度为1的标量值,无法直接传入向量。要实现case_when()中TRUE ~ v1的逻辑,只需将原列作为最后一组条件-值对,条件设为TRUE(匹配所有未被前面条件覆盖的行)即可:

dt[, v2 := fcase(is.na(v1), "0",
                 TRUE, v1)]

验证结果

执行上述代码后,输出结果与dplyr版本完全一致:

v1 v2
1:    1  1
2:    2  2
3:    3  3
4: <NA>  0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:20:03