2017-04-12 128 views
0

我正在嘗試使用R編寫多個NCDF4文件。我有大量文件需要在分析中讀取並輸出到新的NCDF4文件。 我有下面的代碼來創建和寫入到一個單獨的NCDF4文件。此代碼適用於創建和寫入文件。 我需要一些代碼來替換ncfname < - 「ABC123.nc」並循環,從而爲每個分析的文件生成一個NCDF4新文件當我嘗試使用一個循環,就像在R中一樣,如果失敗。在NCDF4包希望看到「NC」的延伸。 我的代碼如下。任何人都可以在這方面的幫助?寫入多個NCDF4文件

#####Write NCDF4 files############################################# 
################################################################### 

tunits<-"days since 1600-01-01 00:00:00" 

#Define dimensions 
################################################################## 
londim<-ncdim_def("Lon","degrees_east",as.double(Lon)) 
latdim<-ncdim_def("Lat", "degrees_north",as.double(Lat)) 
timedim<-ncdim_def("time",tunits,as.double(time)) 

#Define variables 
################################################################## 
fillvalue<-(-1e32) 

dlname<-"2 meter air temperature" 
dlname2<-" 2 meter max air temperature" 

tmp_def<-ncvar_def("Data1","deg_C", 
    list(londim,latdim,timedim),fillvalue,dlname,prec = "double") 
tmp_def2<-ncvar_def("Data2","deg_C", 
list(londim,latdim,timedim),fillvalue,dlname2,prec = "double") 

#Create Ncdf4 file and put arrays 
################################################################## 
ncfname<-"ABC123.nc" 

ncout<-nc_create(ncfname,list(tmp_def,tmp_def2),force_v4=T) 

#Put variables 
################################################################# 

ncvar_put(ncout,tmp_def,Data2,start=NA,count = NA) 
ncvar_put(ncout,tmp_def2,Data1, start= NA,count = NA) 


ncatt_put(ncout,"Lon","axis","X") 
ncatt_put(ncout, "Lat", "axis", "Y") 
ncatt_put(ncout, "time","axis", "T") 

################################################# 
title<-c(1:2) 
names(title)<-c("jack","jill") 
title<-as.data.frame(title) 
################################################ 

# attributes # the 0 designates the attribute as global 
########################################################### 
ncatt_put(ncout,0,"Make_NCDF4_File",1, prec="int") 
ncatt_put(ncout,0,"XXXXXX",1,prec="short") 
ncatt_put(ncout,0,"AR000087828",1, prec="short") 
ncatt_put(ncout,0,"description","this is the script to write NCDF4files") 


#Close file and write date to disk 
########################################################## 
nc_close(ncout) 

回答

0

循環通過數據和創建netCDF4文件中的每個迭代將工作,只要你的循環設置首先,你的循環語法必須是正確的,你的例子沒有你的循環,所以我不能直接發表評論,其次,你必須得到不同的字符串來命名你的NetCDF文件,就像你有指出,你可以使用這樣的東西

ncfname <- sprintf('ABC%03d.nc', i) 

如果我們假設i是您的循環迭代器。當然,您可以使用任何其他變量來幫助sprintf構建文件名。請注意正確的格式化語法。關於sprintf的好處在於你有很多格式控制,並且可以很容易地在格式字符串中包含諸如'.nc'擴展名之類的東西,因此它包含在每個文件名中。 paste將是構建文件名的另一個有用的功能,如果這對您更好。

最後,要意識到循環在腳本中的位置。我的意思是,如果他們不必這樣做,就不會一遍又一遍地重複變量。在你的情況下,任何不依賴於或創建ncfname的包函數(例如,ncdim_def)都可以放置在循環之外並用於構建每個netCDF文件。一般而言,除了ncvar_put輸入的實際數據外,每個文件相似時,尺寸和變量對象可以在循環外定義。

+0

謝謝nawendt – ian

+0

我會努力做到這一點,希望能回到你身邊證實成功 – ian

+0

謝謝nawendt。這段代碼完美地工作。我只需要解決它爲什麼不循環。但那是一個不同的問題。伊恩 – ian