Slope calculation in R after removing zero or NA values

473 Views Asked by At

I am calculating trend of a time series raster against time data but because of NA and Zero values I am not getting correct results.

In the example below values of a pixel is given. Because of zero values I am getting the value of slope as -23.275 instead of 3.897

time Value
1     289
2     289
3     353
4     305
5     0
6     0
7     385
8     0
9     0
10    305
11    0
12    0
13    0
14    0
15    0

correct form should be like this

Time Value
1     289
2     289
3     353
4     305
7     385
10    305

My sample code is

library(raster)

setwd("F:\\PHD_work\\Paper_work\\EOS\\New folder")
eos = stack(list.files(pattern='*.img'))
time = 1:nlayers(eos)
f_slope=function(x) { if (is.na(x[1])){ NA } else { m = lm(x ~ time); summary(m)$coefficients[2] }}
z = calc(eos, f_slope)
y = writeRaster(z, filename = "slope", format = "HFA")
1

There are 1 best solutions below

9
On BEST ANSWER

The data is in S4, to change the values in z using the @

z@data@values <- z@data@values[z@data@values  > 0]



But since this was not said in the Question, I'll keep the normal filtering also

using dplyr

eos <- eos %>% na.omit() %>% filter(Value>0)

or base

eos <- eos[complete.cases(eos),]
eos <- eos[eos$Value>0,]