简体   繁体   中英

Turn `=` into `<-` using only base R

Problem

  1. Turn assignment equal signs into assignment arrows.
  2. Use base R only (no styler or formatR ).

Context

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

Example

Input:

f = function(x = 1){}

Desired output:

f <- function(x = 1){}

Posted in-issue but might as well try for some SO 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"
## }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM