loop to open, get variables and export multiple nc files in r

937 Views Asked by At

I have over 60 nc files for specific coordinates which contain only one variable. I want to extract the variables (tasmax) from them in a csv file. The code for one file is:

ncdata <- nc_open("data.nc")
tasmax<-ncvar_get(ncdata,"tasmax")
nc_close(ncdata)
tasmax<-as.data.frame(tasmax)
write.csv2(tasmax,file="data.csv")

I tried to make a loop for all the files but always got wrong..Any ideas?

1

There are 1 best solutions below

0
On

I follow this code and worked:

df=NULL

files<- list.files('tasmax/ssp370',pattern='*.nc',full.names=TRUE)

for(i in seq_along(files)) {
 nc = nc_open(files[i])code 
tasmax<-ncvar_get(nc,"tasmax")
nc_close(nc)
cbind(df,tasmax)->df
}
df<-as.data.frame(df)

write.csv2(df,file="data.csv")