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.L oop - unique
для Region и Crop, извлеките данные для отдельных файлов и запишите их на диск.
# 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)
}
}