# Converts a file of Tuscon format tree ring data to long-format # This reads original Tucson ring width files from each site, per species, and EW/LW/RWL #and combines into one site RW file with species and measurement type (EWR/LWR/RWL) as columns # FOlder setup: # "LTER Long Form" #"Site" folder should contain one folder per site, with a folder called "Tucson RWL" within it # In the Tucson RWL folder should only be rwl, ewr, and lwr files to read into the script #"Long form RWL" will be the output folder # Open packages library(dplR) library(reshape) library(reshape2) library(dplyr) library(stringr) library(tools) # Set working directory to site folder setwd("/Users/tem583/OneDrive - Harvard University/LTER long form/Sites") # List of site folders folder_list = list.files() for(j in 1:length(folder_list)){ setwd(file.path("/Users/tem583/OneDrive - Harvard University/LTER long form/Sites", folder_list[j], "/Tucson RWL")) # Compile a list of file names in that folder file_list = list.files() long_site <- data.frame() # Convert .rwl to .csv with ring width value for each individual and year for(i in 1:length(file_list)){ #read the chronology setwd(file.path("/Users/tem583/OneDrive - Harvard University/LTER long form/Sites", folder_list[j], "/Tucson RWL")) a <- read.rwl(file_list[i]) a <- tibble::rownames_to_column(a, "Year") #drop extension from filename b <- tools::file_path_sans_ext(basename(file_list[i])) #read file extension (EW/LW/RWL) ext <- file_ext(file_list[i]) site <- word(b,1,sep = "_") # Set working directory to folder with converted csv setwd("/Users/tem583/OneDrive - Harvard University/LTER long form/Long Form RWL") # Convert from Tucson to long format using "melt" function long <- melt(a, na.rm = TRUE, id.vars = 1) colnames(long) <- c("year","core","rw") long$species <- word(b, 2, sep = "_") long$site <- word(b,1,sep = "_") long$type <- ext long <- long[c("site","species","core","type","year","rw")] long_site <- rbind(long_site,long) } write.csv(long_site, file=paste(site,".csv",sep=""), row.names = FALSE, quote=FALSE) }