Reputation: 2533
I have several netcdf files that i want to extract to text file but I found that the first value (from the first file)of A,B,C
in the output file es55.txt
is repeated for the whole text file so the loop does not take values from other files
the code:
library("ncdf")
a<-list.files("C:\\Users\\CLdata", "*.nc", full.names = TRUE)
dt <- as.POSIXct(strptime(basename(a), "data_%Y%m%dT%H%M%S_%Y%m%dT%H%M%S", tz = "GMT"))
for(i in 1:length(a)){
f <- open.ncdf(a[i])
A = get.var.ncdf(nc=f,varid="Sgf",verbose=TRUE)
B <- get.var.ncdf(nc=f,varid="gh")
C <- get.var.ncdf(nc=f,varid="jk")
df=data.frame(date = dt, A, B ,C ) }
write.table(df,file="es55.txt")
example:
"date" "A" "B" "C"
"1" 2010-09-29 23:59:59 0.0191961424604022 216 216
"2" 2010-09-29 23:59:59 0.0191961424604022 216 216
"3" 2010-09-29 23:59:59 0.0191961424604022 216 216
"4" 2010-09-29 23:59:59 0.0191961424604022 216 216
"5" 2010-09-29 23:59:59 0.0191961424604022 216 216
Upvotes: 1
Views: 132
Reputation: 1383
It might be the fact that you're writing to the file outside of the loop. Try to append to the file inside of the loop as follows:
library("ncdf")
a <-list.files("D:\\Cloud\\Dropbox\\Documents\\Shared\\", "*", full.names = TRUE)
dt <- as.POSIXct(strptime(basename(a), "data_%Y%m%dT%H%M%S_%Y%m%dT%H%M%S", tz = "GMT"))
for(i in 1:length(a)){
f <- open.ncdf(a[i])
A = get.var.ncdf(nc=f,varid="Sgf",verbose=TRUE)
B <- get.var.ncdf(nc=f,varid="gh")
C <- get.var.ncdf(nc=f,varid="jk")
df <- data.frame(date = dt, A, B ,C )
print(df) # For debugging purposes
if (i==1) {
write.table(df,file="es55.txt")
}
else {
write.table(df,file="es55.txt", append = TRUE)
}
Otherwise, what is the output of the print(df) statement in each loop run?
Upvotes: 2