[R] Need help with renaming sub-directories and its files after attribute vales from a shapefile

P Mads madsenpw at gmail.com
Wed Sep 14 22:41:39 CEST 2016


Hello,
Keep in mind I am VERY new to using R... What I am trying to do is package
hundreds of files into a new sub-directory. I was able to accomplish this
with the code below. HOWEVER, I have come to find that instead of merely
having to name the new sub-directory after the 7-digit numeric prefix in
the file names, the sub-directories AND the corresponding files all have to
be named after a certain attribute value in a shapefile ("DOQ_Index").
Basically, what I need to do is 1) match the filenames' 7-digit prefix to
the "ID" attribute field in the shapefile (eg. 4310950 = '4310950' - "ID"
field); then, 2) for those matches, I need to create a sub-directory based
on a DIFFERENT attribute field value ("CODE" field) and then 3) rename the
matching files based on the "CODE" attribute field and move those files to
the new sub-directory. Whew. Does that make sense?? Anyway, can someone
help me with this while keeping the basic code structure below?
Thank you! - Pmads

#read in the QuadIndex *-- I recently added this step thinking this is how
to read the shapefile*
q<- readOGR(dsn="C:/GeoHub/Test", layer="DOQ_Index")

#set the working directory
setwd("C:/GeoHub/Test/TestZip")

#get a list of directories
dlist<- list.dirs()
#remove the first vector
dlist<- dlist[-1]

#If the files are all in the working directory
  vec1 <-  list.files()
  vec1

  lst1 <- split(vec1,substr(vec1,3,9))

  #Create the sub-directory based on the first 7 numeric prefix
  sapply(file.path(getwd(),names(lst1)),dir.create)

  #Move the files to the sub-directory
  lapply(seq_along(lst1), function(i)
file.rename(lst1[[i]],paste(file.path(names(lst1[i])), lst1[[i]],sep="/")))
  list.files(recursive=TRUE)

	[[alternative HTML version deleted]]



More information about the R-help mailing list