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

如何在R语言的with表达式中反向引用其作用域?

优化重复R代码的几种优雅写法

1. 提前存储筛选后的子集

最直接的方式是把筛选结果存入变量,后续重复使用,避免多次执行相同的子集操作:

filtered_mtcars <- mtcars[mtcars$cyl > 4, ]
aggregate(filtered_mtcars, by = list(filtered_mtcars$gear), min)

2. 用dplyr实现流式操作

如果使用tidyverse工具链,管道语法能让代码逻辑更连贯,完全消除重复:

library(dplyr)

mtcars %>%
  filter(cyl > 4) %>%
  group_by(gear) %>%
  summarise(across(everything(), min))

3. 优化基础R的with/within用法

原代码的with没有充分利用作用域特性,改进后可以避免重复写子集:

# 用with结合预存子集
filtered <- subset(mtcars, cyl > 4)
with(filtered, aggregate(filtered, by = list(gear), min))

# 更简洁的within写法,用.SD代表当前数据框
within(subset(mtcars, cyl > 4), {
  aggregate(.SD, by = list(gear), min)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:24:25