2

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.

2 Answers 2

5

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)
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much it's exactly what i want , have a nice day ;-)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.