0

I need to use the functions detrend() and chron() from the dplR package on >300 tree-ring width datasets (.rwl files), of differing lengths. Rather than copying and pasting the code for each object, I would like to do this simultaneously. After some google-ing, it looks like I need to develop a for loop, but I have not had much luck after some troubleshooting. Could someone help put me in the right direction? Below is my current code.

    ##read data files in
    or001 <- read.rwl("or001.rwl", format = "tucson")
    or002 <- read.rwl("or002.rwl", format = "tucson")
    or004 <- read.rwl("or004.rwl", format = "tucson")

    #detrend - negex method
    or001.negex <- detrend(or001, nyrs = NULL, method = "ModNegExp", f = 0.5,
                   pos.slope = FALSE)
    or002.negex <- detrend(or002, nyrs = NULL, method = "ModNegExp", f = 0.5,
                   pos.slope = FALSE)
    or004.negex <- detrend(or004, nyrs = NULL, method = "ModNegExp", f = 0.5,
                   pos.slope = FALSE)

    #build final chronology 
    or001.negex.crn <- chron(or001.negex, prefix = 'OR')
    or002.negex.crn <- chron(or002.negex, prefix = 'OR')
    or004.negex.crn <- chron(or004.negex, prefix = 'OR')

    #export final chronologies
    write_excel_csv(or001.negex.crn, path = "or001.negex.crn.csv")
    write_excel_csv(or002.negex.crn, path = "or002.negex.crn.csv")
    write_excel_csv(or004.negex.crn, path = "or004.negex.crn.csv")

    
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    https://stackoverflow.com/a/24376207/3358227 is a good place to start, translating "data frame" in the link to the output from `read.rwl(.)`. – r2evans Sep 13 '21 at 20:57
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Sep 14 '21 at 01:50

1 Answers1

1

Consider reading the datasets in a list and apply the same function by creating a function ('f1')

f1 <- function(file, filenm) {
     dat <- read.rwl(file, format = "tucson")
     negex <-  detrend(dat, nyrs = NULL, method = "ModNegExp", f = 0.5,
                   pos.slope = FALSE)
     negex.crn <- chron(negex, prefix = 'OR')
      write_excel_csv(negex.crn, path = filenm)
     return(negex.crn)
}
# // get all the files with the `.rwl` pattern
# // from the current working directory
files <- list.files(pattern = "\\.rwl$", full.names = TRUE)
# // change the file names by replacing the suffix with negex.crn.csv
# // loop over the files, and apply the function
nm1 <- sub("\\.rwl", "negex.crn.csv", basename(files))
Map(f1, file = files, filenm = nm1)
akrun
  • 874,273
  • 37
  • 540
  • 662