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

需求:将指定dplyr命令封装为含4个参数的R自定义函数

自定义R函数实现灵活的数据处理

没问题,我帮你把给定的dplyr代码封装成了一个通用的自定义R函数,完全满足你要求的四个参数设置,还额外支持传递scales函数的可选参数,让它能适配更多场景:

library(dplyr)
library(scales)

process_scaled_data <- function(df, filter, scales_func, mutate_var, ...) {
  df %>%
    filter({{ filter }}) %>%
    mutate({{ mutate_var }} := scales_func({{ mutate_var }}, ...)) %>%
    select({{ mutate_var }}) %>%
    pull()
}

参数说明

  • df:目标数据框,比如你示例里的Cash_Collateral
  • filter:dplyr::filter()函数内的任意过滤条件,比如Collateral == 'Non-Residential'
  • scales_func:scales包中的任意函数,比如scales::percent、scales::comma、scales::dollar等
  • mutate_var:需要处理的待突变变量,比如LRF_Net_ActualVsForecast
  • ...:可选参数,用来传递给scales_func的额外参数(比如percent函数的accuracy=0.1)

使用示例

用你提供的场景调用这个函数,效果和原代码完全一致:

# 调用函数得到结果
val <- process_scaled_data(
  df = Cash_Collateral,
  filter = Collateral == 'Non-Residential',
  scales_func = scales::percent,
  mutate_var = LRF_Net_ActualVsForecast,
  accuracy = 0.1
)

这个函数的优势在于复用性——你可以轻松更换数据框、过滤条件、目标变量和scales函数,比如换成用scales::comma处理数值,或者过滤其他条件:

# 另一个使用场景示例
another_val <- process_scaled_data(
  df = Cash_Collateral,
  filter = Collateral == 'Residential',
  scales_func = scales::comma,
  mutate_var = Some_Numeric_Variable,
  big.mark = ","
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:42:35