Read Multiple raster with the same name contained in different folders

Kevin López Reyes

I am a R beginner and I want to read multiple ASCII text files with the same name but located in different folders. I have a folder that contains other folders named after different species (e.g. spp1). Inside each species folder, different there are folders for different models (e.g. model1) and, inside that there are ASCII files with the same name (e.g. var1.asc).

Example listing:

$ find path -type f

For each species, I need to read the ASCII files of all models it has and calculate the median of the values between models.

I tried first to create the file path for the spp1, for example:

## Create a list file with the the species ##
data <-list.files(pattern=".csv")
## Create the names of all the species by reading the files and deleting 4 characters (".csv") ##
for (i in 1:length(names)){
   names <- substr(data[i],1,nchar(data[i])-4)

## Then i tried to read in loop the ascii files only saves me the last ascii, not a list of all ##
## Once i have the names i create all the paths for the species ##
   path <- paste0("mypath", names)
## Then i create the subfolders for each model with and list that contains this names ##
   path_m <- paste0(path, Model[i])
   for (i in 1:length(names)){
      models <- list.files(path_m,
                     pattern = ".asc",
                     full.names = TRUE)
      stack <- raster::stack(models)}

## Calculate the median ##

I would appreciate any help and thank you so much for your time.


The name variable it is defined here as:

names <- substr(data[i],1,nchar(data[i])-4)

The original code is (formatted by editor):


## crear un listado de los nombres de mis especies ##
BASEDIR <- "D:/7_Doctorado/Sceloporus/3_Models/kuenm"

data <- list.files(file.path(BASEDIR, "1_Joint"), pattern=".csv")

for (i in 1:length(data)) {
    names <- substr(data[1], start=1, stop=nchar(data[1]) - 4)

    path_cal <- file.path(BASEDIR, paste0("ResultCalibracion_", names))
    cal_res <- read.csv("best_candidate_models_OR_AICc.csv")
    row_names <- cal_res[, 1]

    for (i in 1:length(row_names)) {
        path <- file.path(BASEDIR,
                          paste0("Final_Models_", names),
        models <- list.files(path,
                             pattern = "M_median.asc",
                             full.names = TRUE)
        stack <- raster::stack(models)
    median_sp <- median(models)
    sd_sp <- sd(models)
    setwd(file.path(BASEDIR, "2_Models"))
    writeRaster(median_sp, filename=paste0(names, "_median"), format="ascii")
    writeRaster(sd_sp, filename=paste0(names, "_sd"), format="ascii")

It is hard to understand if you don't have the full context, that is why I prefer to explain the logic behind my question. The code above generates no errors, but the loop only reads the last ASCII file.


I was editing your question (indenting and simplifying the code a bit to facilitate its reading) and maybe I found the error.

In the original code you added, the first statement of the outer loop reads:

names <- substr(data[1], start=1, stop=nchar(data[1]) - 4)

But it probably should use data[i] (with a lower case letter i instead of a digit 1).

To avoid this kind of error, R allows iterating over vectors or lists directly, without the need of indexes. For example, the beginning of the loop:

for (i in 1:length(data)) {
    names <- substr(data[i], start=1, stop=nchar(data[i]) - 4)

Could be rewritten as:

for (filename in data) {
    names <- substr(filename, start=1, stop=nchar(filename) - 4)

Or even using a specialized function to remove the filename extension:

for (filename in data) {
    names <- tools::file_path_sans_ext(filename)
    # Or as you knew the extension ("$" marks end-of-string):
    names <- sub('\\.asc$', '', filename)

Using these kinds of dialects prevents that types of lookalike character typos and off-by-one bugs that are common when using bare indices.

Collected from the Internet

Please contact javaer1[email protected] to delete if infringement.

edited at


Login to comment


Delete file with same name contained in different sub-folders

read multiple files with same name but different extension Python

PyCharm Import files with same name in different folders

Find files with same name in different folders

Merge files with same name in different folders

Windows Phone Classes with same name but different folders

Moving several files to different folders with same name

Delete content of folders with same name in different subdirectories

load multiple files from different folders with same file name in bash-scipt

Copy same file to multiple different folders PowerShell

Same name contained in different street names -

Java - Two classes, same name, same package but in different folders

Open/read multiple .tif images from multiple folders on different levels

gunzip multiple gz files with same compressed file name in multiple folders

Bash: how to copy multiple files with same name to multiple folders

List all files under different folders with same name

How to solve function overloading on Octave from different folders but with the same name?

Asset Catalog: Access images with same name in different folders

2 folders added to PATH contain different files with the same name

How to delete 2 files with the same name from different folders?

Move files with same name in different folders to one folder

Combine files in multiple folders into one folder on Mac or read multiple files in different folders simultaneously in R

Search for text in files of same name in multiple folders of various depths

Move multiple files with the same name into new folders named with the file paths

Unzip multiple zip files into different folders with a particular name

Using multiple javascript service workers at the same domain but different folders

grouping folders with same name

Python script to copy different files from one folder to different sub-folders.with same name as file name

Declaring multiple objects of different classes with the same name

TOP Ranking