I want to name a file according to specific section of the file path. Is it possible to have a substr stop at a path separator?
For example, I want an output file to read "worldclim.csv"
if I am extracting data from this path:"F:\Data\WorldClim\masked\Africa" I want the output file to be named: "worldclim.csv"
Here is an example:
(file.out <- runif(4))
(path <- "F:\\Data\\WorldClim\\masked\\Africa")
(pname <- sapply(path, function(x) substr(x,start=9,stop=17)))
write.csv(file.out, paste0("F:\\Data\\extractions\\", pname, ".csv"), row.names=F)
However, I need to do this for many directories, and the sub-directories inside "Data" have different character lengths.
In short, I want "file.out" to be named after the directory that follows Data. Any ideas?
I guess you can simply split on \\
:
strsplit(path, '\\\\')[[1]][3]
# [1] "WorldClim"
# or
strsplit(path, '\\', fixed = TRUE)[[1]][3]
# [1] "WorldClim"
or use regex
to match 8 characters from start and then extract the pattern until the next \\
:
sub('^.{8}([^\\]+).*$', '\\1', path)
# [1] "WorldClim"