简体   繁体   English

从数据帧在 R 中创建带有 csv 文件的文件夹

[英]Create folders with csv files in R from a dataframe

I have a csv file with several variables, and each variable has several modalities, as illustrated below for example:我有一个包含多个变量的 csv 文件,每个变量都有几种模式,如下图所示:

Region Crop Date Product
     a   aa aaa aaaa
     a   dd ddd ssss
     b   ss eee dddd
     b   cc fff ffff
     c   vv fff gggg
     c   gg ddd rrrr
     d   ff sss tttt
     d   rr ggg gggg

and I want to create several folders according to the modalities of the "Region" variable with several .csv files inside according to the modalities of the "crop" variable obtaining folders like in picture regions folders我想根据“区域”变量的模式创建几个文件夹,里面有几个 .csv 文件,根据“裁剪”变量的模式获取文件夹,如图片区域文件夹

and inside each folder having files for crops like in the picture crops files并且在每个文件夹中都有用于裁剪的文件,例如图片裁剪文件

in summary I want to obtain the data by crop by region.总之,我想按地区按作物获取数据。 I could have the data by crop or by region using the library "tidyverse" but to combine the two "crops files for each region folder" I can't do it if you can help me on it and thank you in advance.我可以使用库“tidyverse”按裁剪或按区域获取数据,但要合并两个“每个区域文件夹的裁剪文件”,如果您能帮助我并提前感谢您,我将无法做到。

1.Make reproducible example data 1.制作可重现的示例数据

df <- data.frame(Region = c("a", "a", "b", "b", "c", "c"),
                 Crop = c("aa", "dd", "ss", "cc", "vv", "gg"),
                 Date = c("aaa", "ddd", "eee", "fff", "fff", "ddd"),
                 Product = c("aaaa", "ssss", "dddd", "ffff", "gggg", "rrrr"),
                 stringsAsFactors = FALSE)

2.Loop through unique values for Region and Crop and extract the data for the individual files and write them to disk. 2. 循环遍历 Region 和 Crop 的unique值,提取各个文件的数据并将它们写入磁盘。

# For each unique Region
#
for(r in unique(df$Region)) {

  # Extract region data
  #
  region_data <- df[df$Region %in% r, ]

  # For each unique Crop within this Region
  #
  for (c in unique(region_data$Crop)) {

    # Extract this region-crop data
    #
    region_crop_data <- region_data[region_data$Crop %in% c, ]

    # Create directory if necessary (would raise warning if directory already exists)
    #
    if (!dir.exists(r)) dir.create(r, recursive = TRUE)

    # Finally save region-crop data to csv
    #
    write.csv(region_crop_data, file.path(r, paste0(c, ".csv")), row.names = FALSE)
  }
}

Loop through the rows, create the folder if it doesn't exist, then write the file out:循环遍历行,如果文件夹不存在则创建文件夹,然后将文件写出:

for(i in seq(nrow(df))){

  myDir <- paste0(df$Region[ i ], "/")
  myCSV <- paste0(myDir, df$Crop[ i ], ".csv")

  if(!dir.exists(myDir)) dir.create(myDir)

  # do some stuff
  # myResult <- ...

  write.csv(myResult, myCSV)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM