[R] find number of consecutive days in NC files by R

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Fri Aug 7 03:16:50 CEST 2020


Hi Ahmet,
I think what you are looking for can be done using run length encoding (rle).

# make up some data
soil_moisture<-sin(seq(0,4*pi,length.out=730))+1.1
dates<-as.Date(as.Date("2018-01-01"):as.Date("2019-12-31"),
 origin=as.Date("1970-01-01"))
# get a logical vector for your condition
under.28<-soil_moisture < 0.28
# show the soil moisture against time
plot(dates,soil_moisture,pch=".",col=under.28+3,cex=2)
abline(h=0.28)
# use rle to get  the runs of low soil moisture
sm.rle<-rle(soil_moisture < 0.28)
cat("Consecutive days below 0.28",
 paste(1:sum(sm.rle$values),sm.rle$lengths[sm.rle$values==TRUE],sep="-"),
 "\n")

Jim

On Fri, Aug 7, 2020 at 3:33 AM ahmet varlı <varli61 using windowslive.com> wrote:
>
> Hi all,
>
>
> There are 365 days of soil moisture NC files and I am trying to find out how many days the values are below and above this certain threshold are repeated by R. However, I couldn't reach exactly what I wanted. For example, Daily soil moisture is below 0.3 without interrupting how many days in 365 days. NC file contains annual soil moisture values daily
>
> nctoarray <- function(ncfname, varid = NA) {   nc <- nc_open(ncfname)
>
> a <- aperm(ncvar_get(nc), c(2,1,3))   nc_close(nc)   a }
>
>
>
> function(x, threshold = 0.28, below = TRUE) {
>
>     if (below) {
>
>         y <- ifelse(x < threshold,1,0)
>
>     } else y <- ifelse(x > threshold,1,0)
>
>
>
>     y2 <- rle(y)
>
>     sel <- which(y2$values == 1)
>
>     max(y2$lengths[sel])
>
> }
>
>
>
> m1 <- suppressWarnings(apply(a,c(1,2), consechours, 0.3, TRUE))
>
>
>
> m2 <- suppressWarnings(apply(a,c(1,2), consechours, 0.4, FALSE))
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list