如何自动创建/保存.rmd文件

问题描述 投票:0回答:2

在 R-Studio 中,在任何目录中创建文件夹和其他元素都相当容易。但如果我想保存 R-Markdown 文件本身,并在目录中使用名称“Template”,我该怎么做?

我对点击“文件>保存”不感兴趣,我希望代码自动将文件保存在目录中。

Creating a folder getwd() #Get Working Directory
setwd("~/Desktop") #Set Working Directory
dir.create("Template") #Create New Folder
setwd("~/Desktop/Template") #Get New Folder as Working Directory

# Create Sub-Directory
dir.create("Results")
dir.create("Code")
dir.create("Data")

上面的代码将创建一系列文件夹。但现在我想将这个 R-Markdown 保存在“Template”文件夹中,名称为“template.rmd”。

谢谢。

r r-markdown
2个回答
1
投票

您好,您可以使用 readLines 读取文件,然后使用 write 保存它。

(自从你

setwd("~/Desktop/Template")
使用
../
从父目录读取)

self<-readLines("../test.Rmd")
write(self,file = "template.rmd")

其中 test.Rmd 是您要复制的文件


0
投票

这在我的工作流程中已经变得很常见。这是我目前的方法:

```{r setup, include=FALSE}
# Load the wbstats package
packages <- c("wbstats", "dplyr", "tidyverse", 
              "openxlsx", "rstudioapi", "wbstats",
              "scales", "ggplot2")
for (pkg in packages) {
  if (!require(pkg, character.only = TRUE)) {
    install.packages(pkg, dependencies = TRUE)
    library(pkg, character.only = TRUE, quietly = TRUE)
  }
}
# Clear workspace
rm(list = ls())
setwd("~/Desktop")
cat("\014")  # Sends a form feed character which clears the console
```

```{r setup, include=FALSE}
# Define base and subdirectories
base_directory <- "~/Desktop/Distribution"
sub_directories <- c("Results", "Code", "Data")
# Extract current filename
filename <- gsub(".*/", "", documentPath()) 
# Delete old work and create base directory
unlink(base_directory, recursive = TRUE)
dir.create(base_directory)
# Create subdirectories
for (sub_dir in sub_directories) {
    dir.create(file.path(base_directory, sub_dir))}
# Move and rename file to Code directory
file_path <- file.path(base_directory, "Code", filename)
file.copy(from = filename, to = file_path)
file.rename(from = file_path, to = file.path(base_directory, "Code", "code.Rmd"))
# Set working directory
knitr::opts_knit$set(root.dir = "/Users/marksheppard/Desktop/Distribution") #Change accordingly
# Clear console again
cat("\014")
```

© www.soinside.com 2019 - 2024. All rights reserved.