简体   繁体   中英

How to create dynamic names in NetCDF file repeatedly with a loop in R studio?

I have successfully transformed the NetCDF file to CSV. However, I had so many files to transform.

Could anyone advise how to do it repeatedly?

Each NetCDF file, for example, X.20000101.nc4.nc, I have to extract three layers but I have 4000 files that I have to extract. I know this can be done in Stata.

Is there any loop in R that I could automatically extract layer 1 (l1), layer 2(l2) and layer 3(l3) and export the CSV file out based on the corresponding date (like 2000101) for each NetCDF file?

Here is my code (it works but very redundant):

```
data20000101 <- nc_open("X.20000101.nc4.nc")

# Extract the 1st layer in X.20000101.nc4.nc
l1 <- brick("X.20000101.nc4.nc", varname="T", "level"=1)

for (n in 1:4) {
  assign(paste("a", n, sep="_"), as.data.frame(l1[[n]], xy=T)) 
}  

write.csv(cbind(a_1,a_2,a_3,a_4), "20000101_l1.csv")

# Extract the 2nd layer in the same file X.20000101.nc4.nc

l2 <- brick("X.20000101.nc4.nc", varname="T", "level"=2)

for (n in 1:4) {
  assign(paste("b", n, sep="_"), as.data.frame(l2[[n]], xy=T)) 
  #read the first layer in the brick as a data frame
}  
level2<-cbind(b_1,b_2,b_3,b_4)
write.csv(level2, "20000101_l2.csv")

# Extract the 3rd layer in the same file X.20000101.nc4.nc

l3 <- brick("X.20000101.nc4.nc", varname="T", "level"=3)
for (n in 1:4) {
  assign(paste("c", n, sep="_"), as.data.frame(l3[[n]], xy=T)) 
  #read the first layer in the brick as a data frame
}  
level3<-cbind(c_1,c_2,c_3,c_4)
write.csv(level3, "20000101_l3.csv")

```

Have a look here: https://www.r-bloggers.com/looping-through-files/

You can iterate over all files within the directory and transform each file according to your solution. You'll have the filename in file.names[i] which you can use for the filename of your csv.

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