数据帧上的 SPI 函数与栅格堆栈

问题描述 投票:0回答:0

我有一个栅格堆栈,代表从 2007 年到 2016 年的每月降水值。

class      : RasterStack 
dimensions : 360, 720, 259200, 120  (nrow, ncol, ncell, nlayers)
resolution : 0.5, 0.5  (x, y)
extent     : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs 
names      : X2007.01.31, X2007.02.28, X2007.03.31, X2007.04.30, X2007.05.31, X2007.06.30, X2007.07.31, X2007.08.31, X2007.09.30, X2007.10.31, X2007.11.30, X2007.12.31, X2008.01.31, X2008.02.29, X2008.03.31, ...

关注这篇文章:https://gis.stackexchange.com/questions/277950/use-spei-function-with-user-specified-parameters-from-a-rasterstack-in-r

我应用此代码来获取 SPI 值:

#transform the raster into a matrix
r.mat <- as.matrix(data)

# Run spi()

funSPImat <- function(x, sc, na.rm=TRUE,...) {
  dat <- ts(x, start = c(2007, 1), end = c(2016, 12), frequency = 12)
  as.numeric((spi(dat, sc, na.rm=na.rm, ...))$fitted) 
}

fitted.mat <- t(apply(r.mat, 1, funSPImat, sc = 3))


# Convert back to raster brick
spi <- setValues(data, fitted.mat)
dates <- seq(as.Date("2007-01-01"), as.Date("2016-12-01"), by="month")
names(spi) <- as.yearmon(dates)

#convert to a dataframe
df = as.data.frame(spi, xy=T)

#pivot longer 
df <- df %>%
  pivot_longer(cols=-c(x, y), 
               names_to = "date", 
               values_to = "spi")

 head(df, 10)
# A tibble: 10 × 4
       x     y date        spi
   <dbl> <dbl> <chr>     <dbl>
 1 -180.  89.8 Jan.2007 NA    
 2 -180.  89.8 Feb.2007 NA    
 3 -180.  89.8 Mar.2007  0.353
 4 -180.  89.8 Apr.2007  2.00 
 5 -180.  89.8 May.2007  1.39 
 6 -180.  89.8 Jun.2007  0.995
 7 -180.  89.8 Jul.2007  0.635
 8 -180.  89.8 Aug.2007  0.951
 9 -180.  89.8 Sep.2007  0.807
10 -180.  89.8 Oct.2007  1.18 

到目前为止一切顺利。

然而,我也直接在数据帧上应用了该方法:

tibble [31,104,000 × 4] (S3: tbl_df/tbl/data.frame)
 $ x   : num [1:31104000] -180 -180 -180 -180 -180 ...
 $ y   : num [1:31104000] 89.8 89.8 89.8 89.8 89.8 ...
 $ date: chr [1:31104000] "2007.01.31" "2007.02.28" "2007.03.31" "2007.04.30" ...
 $ prec: num [1:31104000] 4.92 6.93 15.67 31.74 3.76 ...

#compute the spi
spi_data = spi(prec.df$prec, 3, distribution = "Gamma", na.rm=T)


# Add SPI values as a new column to the original data frame
prec.df <- prec.df %>% 
  mutate(SPI = spi_data$fitted)

我没有得到相同的值

# A tibble: 10 × 5
       x     y date        prec SPI[,"Series 1"]
   <dbl> <dbl> <chr>      <dbl> <ts>            
 1 -180.  89.8 2007.01.31  4.92          NA     
 2 -180.  89.8 2007.02.28  6.93          NA     
 3 -180.  89.8 2007.03.31 15.7  -0.73648272     
 4 -180.  89.8 2007.04.30 31.7  -0.48262324     
 5 -180.  89.8 2007.05.31  3.76 -0.64853122     
 6 -180.  89.8 2007.06.30 41.6  -0.42134334     
 7 -180.  89.8 2007.07.31 37.0  -0.38295926     
 8 -180.  89.8 2007.08.31 53.5  -0.04989971     
 9 -180.  89.8 2007.09.30 43.2  -0.03902929     
10 -180.  89.8 2007.10.31 50.7   0.03538523 

谁能告诉我为什么我得到不同的结果?

r dataframe raster
© www.soinside.com 2019 - 2024. All rights reserved.