How to subtract consecutive daily data with its successor date in netcdf file?

I want to subtract my first daily date of a month with its second date than the second date data with the third date and so on using DIff in R.213-Lon,78-Lat,30-days data. I am getting zero as output.

My code begains:

cdf<-nc_open(file.choose()) //open my netcdf file

rain1 <- ncvar_get( cdf, “RAINNC” ) //extrct varaible

dim(rain1)

[1] 213 78 30

obs1<-array(0,c(213,78,30))// dummay array for output

no<-array(0,c(213,78,30))

for( i in 1 :dim(rain1)[1]){

     for( j in 1 :dim(rain1)[2]){

      for( k in 1 :dim(rain1)[3]){

            if(!is.na(rain1)[3]){

              obs[i,j] <- diff(k ,lag = 1)}

             else { no[i,j] <- NA }
}}}

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You can use something like that

# generate data
my_dates <- as.Date(c("2019-01-01", "2019-01-02", "2019-01-05"), "%Y-%m-%d")
# substract each date data from the preceding one
my_dates[1:(length(my_dates)-1)] - my_dates[2:length(my_dates)]
# see output
Time differences in days
[1] -1 -3

If you need it other way around (substract date data from the following) you can of course simply change the order to my_dates[2:length(my_dates)] - my_dates[1:(length(my_dates)-1)]