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

如何将公式列表传入dplyr::case_match()函数?

如何将公式列表传入dplyr::case_match()

我经常需要在各类场景下对标签或变量名进行大量自定义修改,dplyr::case_match()是很合适的工具,示例代码如下:

library(dplyr)
x <- c("a", "b", "a", "d", "b", "c")

y <- case_match(x,
  "a" ~ 1,
  "b" ~ 2,
  "c" ~ 3,
  "d" ~ 4
)

但公式列表过长时(尤其是涉及长字符串)管理起来很麻烦,我想把这些公式存成列表放在独立配置区,不用每次改代码都深入逻辑部分。尝试直接传入列表时会抛出错误:

labelswitch <- 
       list("a" ~ 1,
       "b" ~ 2,
       "c" ~ 3,
       "d" ~ 4)

y <- case_match(x, labelswitch)

错误信息:Error in case_match(): ! Case 1 (z) must be a two-sided formula, not a list.

目前用封装函数的方法可行,但临时修改标签不够便捷:

# 可行但不够便捷的函数封装方法
cmfun <- function(x) {
  case_match(x,
  "a" ~ 1,
  "b" ~ 2,
  "c" ~ 3,
  "d" ~ 4
  )
}

cmfun(x)

两种直接传入公式列表的方法

1. 使用rlang的解引用运算符!!!

将公式存为列表,用!!!把列表中的元素逐个传入case_match(),这是tidyverse的惯用写法:

library(dplyr)
# rlang通常随dplyr自动加载,显式加载更稳妥
library(rlang)

x <- c("a", "b", "a", "d", "b", "c")

# 独立配置的公式列表
labelswitch <- list(
  "a" ~ 1,
  "b" ~ 2,
  "c" ~ 3,
  "d" ~ 4
)

# 用!!!解引用列表元素
y <- case_match(x, !!!labelswitch)
y
# 输出: [1] 1 2 1 4 2 3

2. 使用基础R的do.call()

通过do.call()将函数和参数列表结合,把输入x和公式列表合并成完整的参数集合:

library(dplyr)

x <- c("a", "b", "a", "d", "b", "c")

labelswitch <- list(
  "a" ~ 1,
  "b" ~ 2,
  "c" ~ 3,
  "d" ~ 4
)

# 构造包含所有参数的列表:第一个元素是x,后续是公式
args <- c(list(x), labelswitch)
y <- do.call(case_match, args)
y
# 输出: [1] 1 2 1 4 2 3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 07:31:15