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
path/spp1/model1/var1.asc
path/spp1/model2/var1.asc
path/spp2/model1/var1.asc
path/spp2/model2/var1.asc

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 ##
setwd("mypath")
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 ##
   median(models)
   }

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


Edit

The name variable it is defined here as:

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

The original code is (formatted by editor):

library(raster)

## 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))
    setwd(path_cal)
    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),
                          paste0(row_names[i],"_NE"))
        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.

leogama

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 [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Asset Catalog: Access images with same name in different folders

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

PyCharm Import files with same name in different folders

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

read multiple files with same name but different extension Python

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

Windows Phone Classes with same name but different folders

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

List all files under different folders with same name

Delete content of folders with same name in different subdirectories

Same name contained in different street names - geocode.arcgis.com

Declaring multiple objects of different classes with the same name

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

Move files with same name in different folders to one folder

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

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

Merge files with same name in different folders

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

Delete file with same name contained in different sub-folders

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

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

Find files with same name in different folders

Copy same file to multiple different folders PowerShell

Moving several files to different folders with same name

grouping folders with same name

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

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

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

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive