简体   繁体   中英

How to extract a date from a nc file name?

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] "file C:\\Users\\data.nc has 3 variables:"
           [1] "short So[lon,lat]  
           [1] "short il[lon,lat]  
           [1] short fg[lon,lat] 

the code is:

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

each file in dirctory represents a date that is written in the name of the file as this 20100929 in this file:

      ext_20100929T235959_272_001_7_1.nc

I would like to add to the output text file a date taken from the name of the file

the output of the code above will give:

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

I want to add the date as:

            "A" "B" "C" "date"
        "1" 500 200 300   ?
        "2" 500 200 300    ?

Any help is welcome

From a vector of strings like this you can extract the date-time with strptime :

 f <- "ext_20100929T235959_272_001_7_1.nc"
 strptime(f, "ext_%Y%m%dT%H%M%S", tz = "GMT")
 ## [1] "2010-09-29 23:59:59 GMT"

 dt <-   as.POSIXct(strptime(f, "ext_%Y%m%dT%H%M%S", tz = "GMT"))

(Assuming the tokenizing is in that format see - help(strptime) for details. )

You can put that "dt" vector into a data.frame, but in your question you are smashing everything to a matrix with t() so you have other issues. I would do all the file names in one hit, using the code above - then build a data.frame(date = dt, A = numeric(length(dt)), ...) etc. and populate the ABC rows in your loop.

Use this to get all the file dates, assuming the format is right and they are consistent:

 dt <-   as.POSIXct(strptime(basename(a), "ext_%Y%m%dT%H%M%S", tz = "GMT"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM