仅使用基础 R 将 `=` 转换为 `<-`
Turn `=` into `<-` using only base R
问题
- 将赋值等号变成赋值箭头。
- 仅使用基数 R(无
styler
或 formatR
)。
上下文
https://github.com/ropensci/drake/issues/562
示例
输入:
f = function(x = 1){}
期望的输出:
f <- function(x = 1){}
已发布,但不妨尝试一些 SO 点:
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"
## }
问题
- 将赋值等号变成赋值箭头。
- 仅使用基数 R(无
styler
或formatR
)。
上下文
https://github.com/ropensci/drake/issues/562
示例
输入:
f = function(x = 1){}
期望的输出:
f <- function(x = 1){}
已发布,但不妨尝试一些 SO 点:
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"
## }