hyat
hyat

Reputation: 1057

Ho to loop inside another loop in R?

I have several files in one folder dir

dir<- list.files("C:\\Users\\data", "*.nc", full.names = TRUE)
for (files in seq_along(dir)){
F = h5read("dir[files]","var")
cet <-F[,,1]*5 }

This loop will read each file in dir and compute cet for only F[,,1] but I have in each file from F[,,1] to F[,,31] (or could be F[,,28])

The structure of F in this file is:

   str(F)
   int [1:360, 1:140, 1:31] 0.2 0.3 0.12

in another files it is

   str(F)
   int [1:360, 1:140, 1:30] 0.8 0.9 0.13

My question is how to tell R to compute cet for F[,,1] ,F[,,2].......... F[,,31] (or could be F[,,28]) for the first file. Then go to the second file and do the same....

Upvotes: 1

Views: 95

Answers (1)

scoa
scoa

Reputation: 19867

library(tools)

outputDir <- "C:\\data"
extension <- ".txt"

cet <- list()

dir<- list.files("C:\\Users\\data", "*.nc", full.names = TRUE)

for (files in seq_along(dir)){
    F = h5read("dir[files]","var")

    cet[[length(cet) + 1]] <- list()
    for(j in seq(1,dim(F)[3])) {

        out.file = file.path(outputDir,
                 paste0(basename(file_path_sans_ext(dir[files])),
                 sprintf("%02d",j),
                 extension))
        writeRaster(F[,,j]*5,filename= out.file)
        cet[[length(cet)]][[j]] <-F[,,j]*5
    } 
}

Upvotes: 1

Related Questions