代码之家  ›  专栏  ›  技术社区  ›  andrewH

R: 穿针引线:查找与外部函数的形式对应的实际参数的名称

  •  0
  • andrewH  · 技术社区  · 7 年前

    功能 strip() 下面试图通过三通管简要报告其运行结果( %T>% ). 因为这个函数依次被传递给包装函数,然后被传递给 purrr::pwalk ,它将一个接一个地为它提供一组数据帧,我想得到它在每个数据帧上的操作的报告以及数据帧名称;也就是说,提供的实际数据帧的名称与形式参数相对应 tib 在下面的函数中。在提供的示例中,这将是 "tst_df" . 在运行函数之前,我不知道这些名称,因为它们是根据从磁盘读取的文件名和各种其他输入构建的。

    enexpr(XX) ,但我也试过 expr(XX) ,并且这两个表达式都应用于 提布 或者点( . ),带或不带前导 !! . 阿尔索 deparse(substitute()) XX 提布 ,和 . 但是没有砰砰的响声。

    我看到名称最初是按pass by值剥离的,然后可能是按管道的每个阶段剥离的,包括 T ,然后,也许,通过( XX = . )在匿名函数中 . 但我知道R+tidyverse会有办法的。我只是希望它不涉及提供一个整数来向上倒计数调用堆栈

    tst_df <- tibble(A = 1:10, B = 11:20, C=21:30, D = 31:40)
    tst_df    
    ################################################################################
    # The strip function expects a non-anonymous dataframe, from which it removes
    # the rows specified in remove_rows and the columns specified in remove_cols. It
    # also prints a brief report; just the df name, length and width.
    strip <- function(tib, remove_rows = FALSE, remove_cols = NULL){
      remove_rows <- enquo(remove_rows)
      remove_cols <- enquo(remove_cols)
      out <- tib %>%
        filter(! (!! remove_rows))  %>%
        select(- !! remove_cols) %T>% (function(XX = .){
          function(XX = .)print(
              paste0("length of ", enxpr(XX), " = ", nrow(XX), " Width = ", ncol(XX)))
              cat("\n")
            })
      out  
    }
    
    out_tb <- strip(tib = tst_df, remove_rows = (A < 3 | D > 38),  remove_cols = c(C, D))
    out_tb
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   Alexis    7 年前

    只需保存的名称 tib 在你开始工作的时候,

    strip <- function(tib, remove_rows = FALSE, remove_cols = NULL) {
      remove_rows <- enquo(remove_rows)
      remove_cols <- enquo(remove_cols)
      tib_name <- as.character(substitute(tib))
      report <- function(out) {
        cat("output length of", tib_name, "=", nrow(out), ", width =", ncol(out), "\n")
      }
    
      tib %>%
        filter(! (!! remove_rows))  %>%
        select(- !! remove_cols) %T>%
        report
    }
    
    out_tb <- strip(tib = tst_df, remove_rows = (A < 3 | D > 38),  remove_cols = c(C, D))
    output length of tst_df = 6 , width = 2