我有一个R脚本,我想从不同的 R 脚本中导入它,操作它的内容(搜索和替换)并使用不同的扩展名保存(.rmd)。
这是 example.R 文件在操作之前的样子:
# A title
# chunkstart
plot(1,1)
# chunkend
Run Code Online (Sandbox Code Playgroud)
这就是example.Rmd操作后的样子:分别用 ```{r} 和 ``` 替换 " # chunkstart" 和 " # chunkend" 。
# A title
```{r}
plot(1,1)
```
Run Code Online (Sandbox Code Playgroud)
我一直在寻找方法来做到这一点,但到目前为止还没有找到。有任何想法吗?
我确信您可以使用正则表达式以更少的代码行来完成此操作。不过它应该可以解决你的问题。
library(magrittr)
readLines('example.R') %>%
stringr::str_replace("# chunkstart", "```{r}") %>%
stringr::str_replace("# chunkend", "```") %>%
writeLines("example.Rmd")
Run Code Online (Sandbox Code Playgroud)
通过以下代码行,您将能够在.R其中的每个文件中应用此“操作”/path_to_some_directory
lapply(list.files('/path_to_some_directory', pattern = ".R$",
full.names = TRUE), function(data) {
readLines(data) %>%
stringr::str_replace("# chunkstart", "```{r}") %>%
stringr::str_replace("# chunkend", "```") %>%
writeLines(paste0(data, "md"))
})
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!