在R的不同子目录中创建相同的文件夹

问题描述

我尝试在 R 的多个子目录中创建相同的文件夹。我以为我可以用 for 循环来做到这一点,但它没有按计划进行

我的文件夹结构是这样的:主目录/Weather_day。 Weather_day 包含文件夹 D0 和 D1。我想在 D0 和 D1 中创建文件夹天气和温度

它试图用 for 循环来做到这一点

pathway = "./Weather_day"
for (i in pathway){
    setwd(i)
    dir.create("weather")
    dir.create("temperature")
}

然而,这样做的结果是在主目录文件夹中创建文件夹。此外,我无法运行此代码两次或更多次,因为它更改了工作目录。

有什么解决办法吗? 提前致谢

解决方法

试试这个。您应该遍历所有子目录。你的 "./Weather_day" 还不够。

setwd("./Weather_day")
pathway <- list.files(full.names = F)
for (i in pathway){
    dir.create(paste0(i,"/weather"))
    dir.create(paste0(i,"/temperature"))
}

前后目录树情况: 之前

weather_day
├── D0
└── D1

之后

weather_day
├── D0
│  ├── temperature
│  └── weather
└── D1
   ├── temperature
   └── weather
,

我建议已经创建了 Weather_day 文件夹。根据您的评论,我的建议如下。

此外,一个函数还提供了额外的用途,例如,如果将来您有一个额外的文件夹,您可以简单地将它添加到该函数中。

wd = getwd()

pathway = paste0(wd,"/Weather_day/")

dir.create(pathway)
    
create_dir = function (x) {
  for (i in x){
    if(!dir.exists(paste0(pathway,i))){dir.create(paste0(pathway,i))}
  }}


create_dir(c("weather","temperature"))

我检查了代码,并使用 if 语句防止覆盖我强烈建议的现有文件夹。但这取决于用例。

编辑

关于您的评论,我调整了我的建议。我不确定这是否正是您要找的:

pathway = paste0(getwd(),"/Weather_day/")

d = c("D0","D1")
x = c("weather","temperature")

create_dir = function (d,x) {
  for (i in d){
    if(!dir.exists(paste0(pathway,i))}
  for (j in x){
    if(!dir.exists(paste0(pathway,i,"/",j))){dir.create(paste0(pathway,j))}
  }}}

create_dir(d,x)

使用上面的代码,您可以获得文件夹 D0 和 D1 中的每个文件夹天气和温度。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...