简体   繁体   中英

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:

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

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.

1.Make reproducible example data

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.

# 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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