r - 仅使用基本 R 将 `=` 转换为 `<-`
问题描述
问题
- 将赋值等号变成赋值箭头。
- 仅使用基数 R(否
styler
或formatR
)。
语境
https://github.com/ropensci/drake/issues/562
例子
输入:
f = function(x = 1){}
期望的输出:
f <- function(x = 1){}
解决方案
已发布,但不妨尝试一些 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"
## }
推荐阅读
- java - java - 如何使用java中的spring test resttemplate将结果转换为特定的模型类型以访问该模型中的字段?
- macos - 在 C:\Program Files\Android\AndroidStudio/Contents 找不到 android studio
- spacy - 如何让泡菜变成空旷的二进制文件
- tensorflow2.0 - 通用句子编码器 fr-en TF 2.x
- java - 如何在 Spring Boot 应用程序中正确使用 Mock?
- java - Teamcity 在 2 个条件之一为真时执行
- hadoop - 当我将文件上传到 HDFS 系统时会发生什么?
- kql - 操作查询以在没有结果的情况下返回 Count = 0
- c# - 在 PAdES 第 4 部分的情况下,带有文档锁定的签名无效
- javascript - 多个实时客户端-服务器(类套接字)连接的最佳选择是什么?