hyat
hyat

Reputation: 1057

Extracting values from nc files in a for loop

I have four netcdf files in a folder and I want to extract some values from these files. the str of the file is:

  [1] "file C:1.DBL.nc has 2 dimensions:"
  [1] "lat   Size: 1"
  [1] "lon   Size: 1"
  [1] "------------------------"
  [1] "file C:\\Users\\data.nc has 3 variables:"
  [1] "short So[lon,lat]  
  [1] "short il[lon,lat]  
  [1] short fg[lon,lat] 

My loop is:

    a<-list.files("C:\\Users\\Data", "*.nc", full.names = TRUE)
    for(i in 1:length(a)){
    f <- open.ncdf(a[i])
    A = get.var.ncdf(nc=f,varid="So",verbose=TRUE)
    B <- get.var.ncdf(nc=f,varid="il")
    C <- get.var.ncdf(nc=f,varid="fg")
    write.table(t(rbind(A,B,C)),file="output-all.txt")}

There is no errors but there is only one line of results in the output text file:

                "A" "B" "C"
            "1" 500 200 300

which should be as many as the number of the files in the folder (4), for instance:

                "A" "B" "C"
            "1" 500 200 300
            "2" 500 200 300
            "3" 500 200 300
            "4" 500 200 300

It seems that the loop is not taking place here.

Upvotes: 0

Views: 1121

Answers (1)

Ujjwal
Ujjwal

Reputation: 3168

Move the write.table command out of the loop. Something like:

a<-list.files("C:\\Users\\Data", "*.nc", full.names = TRUE)
D<-matrix(NA,length(a),3)

for(i in 1:length(a)){
   f <- open.ncdf(a[i])
   A = get.var.ncdf(nc=f,varid="So",verbose=TRUE)
   B <- get.var.ncdf(nc=f,varid="il")
   C <- get.var.ncdf(nc=f,varid="fg")
   D[i,]<-t(rbind(A,B,C))}

write.table(D,file="output-all.txt")

Upvotes: 1

Related Questions