file_name = 'test.nc';
var1_name = 'tmp1';
file2_name = 'test2.nc';
var2_name = 'tmp2';
% Create a netcdf 4 file with a variable
nccreate(file_name, 'myvariable');
% A netcdf 4 file with a variable and its attributes
nccreate(file2_name, var2_name,'Dimensions', {'r' 12 'c' 14 }, 'Datatype' , 'single')
% Write data to the netcdf file
nccreate(file2_name,'var');
ncwrite(file2_name,'var',4.5);
% Modify the data
ncwrite(file2_name,'var',8.3);
% Add an attribute
ncwriteatt(file2_name, var2_name, 'tmp', 'ok');
% Write data from an existing netcdf file to another
data_source = ncread(file2_name, 'var');
nccreate(file_name,'var');
ncwrite(file_name, 'var', data_source);
% Modify the structure of the netcdf file
file_info = ncinfo(file_name,'/')
file_schema.Name = '/';
file_schema.Format = 'netcdf4_classic';
file_schema.Dimensions(1).Name = 'first';
file_schema.Dimensions(1).Length = 2;
file_schema.Dimensions(2).Name = 'second';
file_schema.Dimensions(2).Length = 30;
file_schema.Dimensions(3).Name = 'third';
file_schema.Dimensions(3).Length = 1;
ncwriteschema(file_name, file_schema);
% Modify the structure of the variable 'new_var'
var_info = ncinfo(file_name,'myvariable')
var_schema.Name = 'new_var';
var_schema.Dimensions(1).Name = 'thefirst';
var_schema.Dimensions(1).Length = 2;
var_schema.Datatype = 'double';
ncwriteschema(file_name, var_schema);
#Intall the NetCDF libraries: sudo apt-get install libnetcdf-dev
#Install the ncdf package in R: install.packages("ncdf")
library("ncdf")
# Define netcdf dimensions: name, units and value
dim1 <- dim.def.ncdf("x", "m", seq(1, 200, 40))
dim2 <- dim.def.ncdf("y", "A", 10)
dim3 <- dim.def.ncdf("z", "L", 19)
# Define objets of class var.def.ncdf for the netcdf file with its name, units, dimension(s) and missing value
var1 <- var.def.ncdf("my_var1", "degrees", dim1, -999)
var2 <- var.def.ncdf("my_var2", "degrees", dim1, -999, longname = "things", prec = "integer")
var3 <- var.def.ncdf("my_var3", "degrees", list(dim1, dim2), -999, longname = "An example of 2-dim variable")
# Create a netcdf file with its variables var1, var2 and var3
filename <- "/home/ndiaye/Projets/R/test.nc"
fid <- create.ncdf(filename, list(var1, var2))
# Close the file for having it written to disk
close.ncdf(fid)
# Add a variable to the netcdf file
fid <- open.ncdf(filename, write=TRUE)
var.add.ncdf(fid, var3)
# Write data to a netcdf file
data1 <- c(1,2,3,4,5,6)
put.var.ncdf(fid, var1, data1)
data2 <- matrix(c(128, 2, 1, 0, 8, 9, 180, 31, 8, 24, 5, 7, 81, 62, 541, 0, 54, 36, 0, 54, 36), ncol = 4)
put.var.ncdf(fid, var3, data2, start = c(2,1), count = c(3,1) )
# Close netcdf file access
close.ncdf(fid)