0

I am hoping to be able to break a single excel file into separate excel files based on the value of a single column in the original file (eg. State). Is there any way I can do this in R (preferable) ? Or in Excel ?

VRK
  • 65
  • 4
  • Have you tried this solution? https://stackoverflow.com/questions/9713294/split-data-frame-based-on-levels-of-a-factor-into-new-data-frames – Ronak Shah Mar 22 '21 at 04:00

1 Answers1

1

You could read your excel file into R, then use dplyr and a for loop: library(dplyr)

# Here, you would read in your excel file
# dt <- readxl::read_excel("your_path")

# For the purpose of this example, just using an example dataset:
dt <- PlantGrowth
head(dt)

# Identify unique group
(groups <- unique(dt$group)) # here, you would use your states

# Then filter out each group and save in a loop
for (i in seq_along(groups)) {
        dt2 <- dt %>% filter(group == groups[i])
        write.csv(dt2, paste0("subset_", groups[i], ".csv"), row.names = FALSE)
}

In my home folder, 3 files were created, one per group (see screenshot and preview for subset_trt2.csv).

enter image description here

Rosalie Bruel
  • 1,423
  • 1
  • 10
  • 22