Search code examples
rclassificationdata-manipulation

How to compute sens slope with yearly data frame with value lower than 3?


I have several Tiff files since 1984. For each year and for each pixel of the area I calculated NDVI, NBR and TCW and the mean of each value per year, but now when I try to do this

library(modifiedmk)
library(dplyr)

mkp = function(x){mkttest(x)[[5]]}   # To get the p-value of the slope
sle = function(x){mkttest(x)[[2]]}    # To get the actual slope value
Sens_slope <- annual_means %>% 
      filter(year >= 1984 & year <= 2023) %>%
      group_by(year) %>%
      summarise(
        p.ndvi = mkp(mean_NDVI),
        s.ndvi = sle(mean_NDVI),
        p.nbr = mkp(mean_NBR), 
        s.nbr = sle(mean_NBR),
        p.tcw = mkp(mean_TCW),
        s.tcw = sle(mean_TCW)
     )

the error says Input vector must contain at least three values. I tried several ways, if I turn the value lower than 3 to NA, the whole outcome will be NA, if i use reframe or any other function the result is the same, what is the problem here?

I'm expecting to have a table with p-value and slope for each indices per year.


Solution

  • Based on the information provided, it's challenging to say what the exact problem is. However, here is an example of how you could use sens.slope from the trend package to get the slope and p-value for each pixel and variable.

    library(tidyverse)
    library(trend)
    
    set.seed(333)
    
    # Example dataframe
    df <- data.frame(
      pixelID = rep(c("a", "b", "c"), each = 45),
      year = rep(seq(1980,2024,1),3),
      NDVI = round(rnorm(135,100,30)),
      NBR = round(rnorm(135,1000,250)),
      TCW = round(rnorm(135,300,25))
    )
    
    # Function to apply sens.slope() on each variable
    calculate_sen_slopes <- function(sub_df) {
      ndvi_result <- sens.slope(sub_df$NDVI)
      nbr_result <- sens.slope(sub_df$NBR)
      tcw_result <- sens.slope(sub_df$TCW)
      
      return(data.frame(
        pixelID = unique(sub_df$pixelID),
        NDVI_slope = ndvi_result$estimates,
        NDVI_p.value = ndvi_result$p.value,
        NBR_slope = nbr_result$estimates,
        NBR_p.value = nbr_result$p.value,
        TCW_slope = tcw_result$estimates,
        TCW_p.value = tcw_result$p.value
      ))
    }
    
    # Apply the function to each pixelID group and combine results
    results <- df %>%
      group_by(pixelID) %>%
      do(calculate_sen_slopes(.))
    
    results
    #> # A tibble: 3 × 7
    #> # Groups:   pixelID [3]
    #>   pixelID NDVI_slope NDVI_p.value NBR_slope NBR_p.value TCW_slope TCW_p.value
    #>   <chr>        <dbl>        <dbl>     <dbl>       <dbl>     <dbl>       <dbl>
    #> 1 a          -0.0653        0.845    -6.46       0.0227     0.625      0.0481
    #> 2 b          -0.617         0.200    -0.605      0.853      0.167      0.475 
    #> 3 c          -0.222         0.475     5.79       0.0428    -0.612      0.0644
    

    Created on 2024-06-29 with reprex v2.1.0