【问题标题】:How to simultaneously perform same code on multiple datasets of different lengths in Rstudio?如何在 Rstudio 中同时对多个不同长度的数据集执行相同的代码?
【发布时间】:2021-09-13 20:51:08
【问题描述】:

我需要在超过 300 个不同长度的年轮宽度数据集(.rwl 文件)上使用 dplR 包中的函数 detrend() 和 chron()。我不想为每个对象复制和粘贴代码,而是同时执行此操作。经过一番谷歌搜索,看起来我需要开发一个 for 循环,但经过一些故障排除后我没有太多运气。有人可以帮助我朝着正确的方向前进吗?以下是我当前的代码。

    ##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")

    

【问题讨论】:

标签: r for-loop iteration


【解决方案1】:

考虑读取 list 中的数据集并通过创建函数 ('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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2021-08-29
    • 2021-12-19
    • 2021-10-04
    • 2015-03-24
    • 2019-12-13
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多