Last active
July 13, 2022 08:07
-
-
Save ch-bu/d55e5c5ad06d897e9d309d8f036bd328 to your computer and use it in GitHub Desktop.
Split data frames from number in file path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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