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

只使用R的基数将`=`变成`<-`

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

    问题

    1. 将赋值等号变为赋值箭头。
    2. 仅使用base R(否 styler formatR ).

    https://github.com/ropensci/drake/issues/562

    例子

    f = function(x = 1){}
    

    期望输出:

    f <- function(x = 1){}
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   hrbrmstr    7 年前

    发布在问题中,但不妨尝试一些所谓的pts:

    library(magrittr)
    
    raw_src <- "z = {f('#') # comment
    
    x <- 5
    y = 'test'
        }"
    
    # so we can have some tasty parse data
    first <- parse(text = raw_src, keep.source = TRUE)
    
    # this makes a nice data frame of the tokenized R source including line and column positions of the source bits
    src_info <- getParseData(first, TRUE)
    
    # only care about those blasphemous = assignments
    elements_with_equals_assignment <- subset(src_info, token == "EQ_ASSIGN")
    
    # take the source and split it into lines
    raw_src_lines <- strsplit(raw_src, "\n")[[1]]
    
    # for as many instances in the data frame replace the = with <-
    for (idx in 1:nrow(elements_with_equals_assignment)) {
      stringi::stri_sub(
        raw_src_lines[elements_with_equals_assignment[idx, "line1"]],
        elements_with_equals_assignment[idx, "col1"],
        elements_with_equals_assignment[idx, "col2"]
      ) <- "<-"
    }
    
    # put the lines back together and do the thing
    parse(
      text = paste0(raw_src_lines, collapse="\n"),
      keep.source = FALSE
    )[[1]] %>%
      deparse() %>%
      cat(sep = "\n")
    ## z <- {
    ##     f("#")
    ##     x <- 5
    ##     y <- "test"
    ## }