R语言计算sen趋势

library(terra)
library(trend)

# 设置输入路径(NDVI数据存放位置)
input_path <- "G:/影响因子驱动分析/NDVIdata/ndvi/"

# 设置输出路径(斜率结果保存位置)
output_path <- "G:/论文/lucc/00-20ndvi/"

# 读取NDVI时间序列数据
fl <- list.files(path = input_path, 
                pattern = ".tif$", 
                full.names = TRUE)

# 按文件名排序确保时间顺序正确(重要!)
fl <- fl[order(as.numeric(gsub("\\D", "", fl)))] # 提取文件名中的数字排序
firs <- rast(fl)

# 定义Sen斜率计算函数
fun_slope <- function(x) {
  if (sum(!is.na(x)) < 21) return(NA)  # 21年数据完整性检查
  ts_data <- na.omit(x)
  if (length(ts_data) < 2) return(NA)  # 至少需要2个有效值
  MK_estimate <- trend::sens.slope(ts_data)
  return(MK_estimate$estimate)
}

# 并行计算(4核)
firs_slope <- app(firs, fun_slope, cores = 4)
names(firs_slope) <- "slope"

# 创建输出目录(如果不存在)
if (!dir.exists(output_path)) {
  dir.create(output_path, recursive = TRUE, showWarnings = FALSE)
}

# 保存结果
writeRaster(firs_slope,
            filename = paste0(output_path, "NDVI_Sen_Slope_2000-2020.tif"),
            overwrite = TRUE,
            datatype = "FLT4S")  # 使用浮点型保存小数

# 可视化结果
plot(firs_slope, 
     main = "NDVI变化趋势 (2000-2020)",
     col = colorRampPalette(c("red", "white", "green"))(100))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值