Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Last active September 30, 2021 11:35
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 h-a-graham/b1d56d78a5c785088c377d089030bea9 to your computer and use it in GitHub Desktop.
Save h-a-graham/b1d56d78a5c785088c377d089030bea9 to your computer and use it in GitHub Desktop.
if (!"here" %in% installed.packages()[,"Package"]) install.packages('here')
library(here)
dir_home <- here()
# Function to un-nest all files in sub directories.
unnest_dir <- function(.root, sep="_DIR_SEP_"){
#list all the files in the directory and sub dirs
files <- list.files(.root, full.names = F, recursive = T)
# generate new names for the files
new_names <- lapply(files, function(x) file.path(.root, gsub("/", sep, x)))
# get the full paths for the original names
old_names_full <- lapply(files, function(x) file.path(.root, x))
# map the renaming across all files
mapply(function(x,y) file.rename(x, y),old_names_full, new_names)
#remove redundant folders
lapply(list.dirs(dir_home,recursive = F),
function(x) unlink(x, recursive=T, force=T))
message('Files have been un-nested!')
}
# run un-nest function...
unnest_dir(dir_home)
# function to re-nest files based on the `sep` value in unnest_dir()
renest_dir <- function(.root, sep="_DIR_SEP_"){
# list all files in sub directories
files <- list.files(.root, full.names = F, recursive = T)
# created new names for nested files
nested_names <- lapply(files, function(x) file.path(.root, gsub(sep, "/", x)))
# recreate directories for all files
lapply(nested_names, function(x)
if (!dir.exists(dirname(x))) dir.create(dirname(x), recursive = T))
# get current full path names
current_names <- lapply(files, function(x) file.path(.root, x))
# map renaming function
mapply(function(x,y) file.rename(x, y),current_names, nested_names)
message('Files have been re-nested!')
}
renest_dir( dir_home)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment