r - 在 dplyr 函数中创建和访问动态列名称

标签 r dplyr tidyr rlang tidyeval

library(rlang)
library(dplyr)
library(lubridate)

example = tibble(
  date = today() + c(1:6),
  foo = rnorm(6), 
)

do.some.stuff <- function(data, foo.col){
  sum.col = parse_expr(paste(expr_text(enexpr(foo.col)), "sum", sep="."))
  max.col = parse_expr(paste(expr_text(enexpr(foo.col)), "max", sep="."))
  cnt.col = parse_expr(paste(expr_text(enexpr(foo.col)), "cnt", sep="."))
  
  select(data, date, {{ foo.col }}) %>% 
    filter(!is.na(date) & !is.na({{ foo.col }})) %>% mutate(
      "{{ foo.col }}.cnt" := cumsum( !is.na({{ foo.col }}) ),
      "{{ foo.col }}.sum" := cumsum({{ foo.col }}),
      "{{ foo.col }}.max" := cummax( {{ sum.col }} ),
      "{{ foo.col }}.mu" :=  {{ sum.col }} / {{ cnt.col }}
    )
}

do.some.stuff(example, foo)

所以上面的代码工作得很好,但有点难看,特别是三行 parse_expr 行。我可以将函数重写为:

do.some.stuff <- function(data, foo.col){
  sum.col = paste(expr_text(enexpr(foo.col)), "sum", sep=".")
  max.col = paste(expr_text(enexpr(foo.col)), "max", sep=".")
  cnt.col = paste(expr_text(enexpr(foo.col)), "cnt", sep=".")
  
  select(data, date, {{ foo.col }}) %>% 
    filter(!is.na(date) & !is.na({{ foo.col }})) %>% mutate(
      cnt.col := cumsum( !is.na({{ foo.col }}) ),
      sum.col := cumsum({{ foo.col }}),
      max.col := cummax( {{ parse_expr(sum.col) }} ),
      "{{ foo.col }}.mu" :=  {{ parse_expr(sum.col) }} / {{ parse_expr(cnt.col) }}
    )
}

但情况也好不了多少。有没有其他方法可以完成相同的行为(我不想改变 df 的形状,这部分不取决于我),但踢掉 rlang 依赖项?目前这工作得很好,但如果可能的话,我想要一些更干净/更容易阅读的东西。如果不是很明显的话,我对 R 中的元编程还很陌生,尽管我确实有其他语言的经验。

最佳答案

使用 across.names 参数,或者如果 foo_cnt 等带有下划线就可以,那么只需省略 .names 参数,因为这是默认值。

library(dplyr)
library(tibble)

do.some.stuff.2 <- function(data, col) {
  cnt <- function(x) cumsum(!is.na(x))
  mx <- function(x) cummax(cumsum(x))      
  mu <- function(x) cumsum(x) / cnt(x)
  data %>%
    select(date, {{col}}) %>%
    filter(!is.na(date) & !is.na({{col}})) %>%
    mutate(across({{col}}, lst(cnt, sum=cumsum, max=mx, mu), .names = "{.col}.{.fn}" ))
}
# test
do.some.stuff.2(example, foo)

给予:

# A tibble: 6 x 6
  date             foo foo.cnt   foo.sum   foo.max    foo.mu
  <date>         <dbl>   <int>     <dbl>     <dbl>     <dbl>
1 2021-02-11 -0.000202       1 -0.000202 -0.000202 -0.000202
2 2021-02-12  0.363          2  0.363     0.363     0.181   
3 2021-02-13  1.27           3  1.63      1.63      0.543   
4 2021-02-14  1.50           4  3.13      3.13      0.781   
5 2021-02-15  1.00           5  4.13      4.13      0.826   
6 2021-02-16 -0.458          6  3.67      4.13      0.612 

关于r - 在 dplyr 函数中创建和访问动态列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66148461/

相关文章:

r - 根据预设条件汇总数据并添加 (0,1) 标志

r - 填充 R data.frame 中每行中缺失的元素

r - 使用灵活的调用(在循环中使用)从宽到长的不同宽度的数据透视

r - 使用 `.value` 和 `pivot_longer()` 时如何将后缀附加到 `names_pattern`

r - 不同大小矩阵的相同内存使用

r - 指定图例列中的因子数

r - ggplot2 散点图标签

r - Shiny 的 selectInput 从下拉列表中选择所有内容

r - R 中的慢速点积

sql - 在多个数据集中查找相同的行