1

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 Answers1

0

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)]

  • Thanks for the reply. But I am having 3-dimensional data and it is output has to stored in an array. like: dummy array: obs1<-array(0,c(213,78,30)) which represents lat long and daily data of month. SO I have to work on 3dim and data also contains NA values also. and I should insert your "my_dates[2:length(my_dates)] - my_dates[1:(length(my_dates)-1)]" in my code obs1<-array(0,c(213,78,30)) no<-array(0,c(213,78)) 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]){ should i write here – Jyoti Lodha Aug 01 '19 at 11:36
  • @JyotiLodha Maybe you can update your question with [reproducible data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and expected output? –  Aug 01 '19 at 11:43