Skip to content

Instantly share code, notes, and snippets.

@ch-bu
Last active July 13, 2022 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ch-bu/d55e5c5ad06d897e9d309d8f036bd328 to your computer and use it in GitHub Desktop.
Save ch-bu/d55e5c5ad06d897e9d309d8f036bd328 to your computer and use it in GitHub Desktop.
Split data frames from number in file path
library(fs)
library(tidyverse)
mpg_samples <- map(1:40, ~ slice_sample(mpg, n = 20))
# Create data frames and store them to disk
dir_create(c("chapters/01_improve_reading_files/reprex_files"))
iwalk(mpg_samples[1:9],
~ write_csv(.x,
paste0("chapters/01_improve_reading_files/reprex_files/",
.y, "_b.csv")))
iwalk(mpg_samples[10:20],
~ write_csv(.x,
paste0("chapters/01_improve_reading_files/reprex_files/",
.y, "_a.csv")))
# Get csv file paths
csv_files <- dir_ls("chapters/01_improve_reading_files/reprex_files//",
glob = "*.csv", type = "file")
# Get data
dframe <- read_csv(csv_files, id = "filename")
# Split data frames by number in the filename
dframes_split <- dframe %>%
extract(filename, into = c("letter"),
regex = ".*\\d{1,2}_(.)\\.csv$",
remove = FALSE) %>%
mutate(number = as_factor(letter)) %>%
group_split(letter)
# Store split in separate variables
a <- dframes_split[[1]]
b <- dframes_split[[2]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment