Writing data to a netCDF file with R

前端 未结 1 916
广开言路
广开言路 2021-01-07 04:49

I am trying to use the data on my own .csv file to create a netCDF file using the R package \"ncdf4\". My dataset is composed by 3 columns: longitude, latitude and temperatu

相关标签:
1条回答
  • 2021-01-07 05:33
    library(ncdf4)
    
    filename="time.nc"
    
    xvals <- seq(-177.5, 177.5, 5)
    yvals <- seq(-87.5, 87.5, 5) 
    nx <- length(xvals)
    ny <- length(yvals)
    lon1 <- ncdim_def("longitude", "degrees_east", xvals)
    lat2 <- ncdim_def("latitude", "degrees_north", yvals)
    
    time <- ncdim_def("Time","months", 1:12, unlim=TRUE)
    mv <- -999 #missing value to use
    var_temp <- ncvar_def("temperature", "celsius", list(lon1, lat2, time), longname="CRU_Global_1961-1990_Mean_Monthly_Surface_Temperature_Climatology", mv) 
    
    ncnew <- nc_create(filename, list(var_temp))
    
    print(paste("The file has", ncnew$nvars,"variables"))
    #[1] "The file has 1 variables"
    print(paste("The file has", ncnew$ndim,"dimensions"))
    #[1] "The file has 3 dimensions"
    
    # Some fake dataset based on latitude, to check whether the data are
    # written in the correct order
    data <- rep(yvals, each=nx)
    
    # Add random -999 value to check whether missing values are correctly
    # written
    data[sample(1:(nx*ny), 100, replace = FALSE)] <- -999
    ncvar_put(ncnew, var_temp, data, start=c(1,1,1), count=c(nx,ny,1))
    
    # Don't forget to close the file
    nc_close(ncnew)
    
    # Verification
    library(rasterVis)
    out <- raster("time.nc")
    levelplot(out, margin=FALSE)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题