处理单个nc文件

首先将nc文件转为整的tiff

library(terra)
library(raster)
library(readxl)
library(ncdf4)

# 读取NetCDF文件
nc_file <- brick("C:\\Users\\HP\\Downloads\\tasmax_hadukgrid_uk_1km_day_20220801-20220831.nc", varname = "tasmax")


# 保存为TIFF格式
writeRaster(nc_file, "C:\\Users\\HP\\Downloads\\202208.tif", format = "GTiff", overwrite = TRUE)

再分出来每天的波段到一个文件夹里

# 加载必要的库
library(raster)
library(pbapply)

# 指定多波段TIFF文件的路径
multiband_tiff_path <- "C:\\Users\\HP\\Downloads\\202208.tif"

# 使用stack函数读取多波段TIFF文件
multiband_tiff <- stack(multiband_tiff_path)

# 检查读取的多波段数据
print(multiband_tiff)

# 指定输出文件夹路径
output_folder <- "D:\\data\\bd"

# 确保输出文件夹存在,如果不存在则创建
if (!dir.exists(output_folder)) {
  dir.create(output_folder)
}

# 循环遍历每个波段并分别保存为单独的GeoTIFF文件
# 使用pblapply来添加进程条
output_files <- pblapply(1:nlayers(multiband_tiff), function(i) {
  # 构建输出文件名
  output_file <- file.path(output_folder, paste0("bio_200_", i, ".tif"))
  
  # 提取当前波段
  current_band <- multiband_tiff[[i]]
  
  # 将当前波段写入新的GeoTIFF文件
  writeRaster(current_band, output_file, format = 'GTiff', overwrite = TRUE)
  
  # 返回输出文件名
  return(output_file)
})

# 输出完成的提示信息
cat("All bands have been successfully exported to", output_folder, "\n")

可提取出任意一年一个月内所有天所有地区温度的数据,并整合到一个csv里

 载入必要的库
library(raster)
library(sp)

# 读取 CSV 文件
locations <- read.csv("D:\\data\\filename2.csv")

# 查看数据框的结构,确认最后两列是经度和纬度
str(locations)

# 提取最后两列作为经度和纬度
longitude <- locations$gridx  # 经度
latitude <- locations$gridy    # 纬度

# 创建 SpatialPoints 对象
coordinates(locations) <- ~ gridx + gridy

# 获取所有 TIFF 文件的路径
tif_files <- list.files("D:\\data\\bd", pattern = "\\.tif$", full.names = TRUE)

# 遍历每个 TIFF 文件
for (tif_file_path in tif_files) {
  # 读取 TIFF 文件
  tif_file <- raster(tif_file_path)
  
  # 打印文件名
  print(paste("Processing:", tif_file_path))
  
  # 提取第一个波段
  band1 <- tif_file[[1]]
  
  # 提取每个点的温度值,使用 buffer 参数
  temperature_values <- extract(band1, locations, buffer = 1000)  # 使用 1000 米的缓冲区
  
  # 获取文件名中的数字作为列名
  file_name <- basename(tif_file_path)  # 获取文件名
  column_name <- gsub("\\D", "", file_name)  # 提取文件名中的数字
  
  # 创建一个新的列来存储平均温度
  average_temperatures <- numeric(nrow(locations))  # 初始化新列
  
  # 查看提取的温度值
  for (i in 1:nrow(locations)) {
    temp_values <- temperature_values[[i]]
    
    # 将字符型向量转换为数值型
    temp_values_numeric <- as.numeric(temp_values)
    
    # 计算平均值
    average_temperature <- mean(temp_values_numeric, na.rm = TRUE)  # na.rm = TRUE 用于忽略 NA 值
    
    # 将平均温度存储到新的列中
    average_temperatures[i] <- average_temperature
  }
  
  # 将提取的温度值添加到 locations 数据框中
  locations[[column_name]] <- average_temperatures
}

# 将更新后的数据框写入新的 CSV 文件
write.csv(locations, "D:\\data\\bd\\bdwd\\updated_filename2.csv", row.names = FALSE)
# 提示完成
print("Average temperatures have been added to the CSV file.")

批量处理多个nc文件

批量转为Tiff

# 加载必要的R包
library(raster)   # 用于处理栅格数据
library(terra)    # 更高效的栅格处理工具
library(readxl)   # 用于读取Excel文件
library(ncdf4)
# 设置工作路径
WorkPath <- "D:\\data\\min"
setwd(WorkPath)


# 批量处理所有NetCDF文件,将其转换为GeoTIFF格式
files <- list.files(WorkPath, pattern = "*.nc", full.names = TRUE)

for (file in files) {
  if (file.exists(file)) {
    # 读取NetCDF文件
    nc_raster <- raster(file, varname = "tasmin", band = 1)
    
    # 构建输出文件名并写入GeoTIFF格式
    out_file <- paste0(tools::file_path_sans_ext(file), '.tif')
    writeRaster(nc_raster, out_file, format = 'GTiff', overwrite = TRUE)
    
    # 打印进度信息
    print(paste(out_file, '已完成'))
  } else {
    print(paste(file, '不存在'))
  }
}

批量将每个tiff分波段

# 加载必要的库
library(raster)
library(pbapply)
library(terra)    # 更高效的栅格处理工具
library(readxl)   # 用于读取Excel文件
library(ncdf4)

# 设置工作路径
WorkPath <- "D:\\data\\min"
setwd(WorkPath)

# 批量处理所有GeoTIFF文件,将其拆分为单波段文件
files <- list.files(WorkPath, pattern = "*.tif", full.names = TRUE)

for (file in files) {
  if (file.exists(file)) {
    # 读取多波段GeoTIFF文件
    multiband_tiff <- stack(file)
    
    # 检查读取的多波段数据
    print(multiband_tiff)
    
    # 指定输出文件夹路径
    output_folder <- "D:\\data\\min\\minbd"
    
    # 确保输出文件夹存在,如果不存在则创建
    if (!dir.exists(output_folder)) {
      dir.create(output_folder, recursive = TRUE)
    }
    
    # 提取原始文件名中的日期部分(格式为201010)
    base_filename <- basename(file)
    date_part <- gsub(".*_(\\d{6})\\d{2}-.*", "\\1", base_filename)  # 提取日期部分(如201010)
    
    # 循环遍历每个波段并分别保存为单独的GeoTIFF文件
    # 使用pblapply来添加进程条
    output_files <- pblapply(1:nlayers(multiband_tiff), function(i) {
      # 构建输出文件名
      output_file <- file.path(output_folder, paste0(date_part, "_", i, ".tif"))
      
      # 提取当前波段
      current_band <- multiband_tiff[[i]]
      
      # 将当前波段写入新的GeoTIFF文件
      writeRaster(current_band, output_file, format = 'GTiff', overwrite = TRUE)
      
      # 返回输出文件名
      return(output_file)
    })
    
    # 输出完成的提示信息
    cat("All bands have been successfully exported to", output_folder, "\n")
  } else {
    print(paste(file, '不存在'))
  }
}

 提取出所有地区全部天数温度的数据,并整合到一个csv里

# 载入必要的库
library(raster)
library(sp)

# 读取 CSV 文件
locations <- read.csv("D:\\data\\filename2.csv")

# 查看数据框的结构,确认最后两列是经度和纬度
str(locations)

# 提取最后两列作为经度和纬度
longitude <- locations$gridx  # 经度
latitude <- locations$gridy    # 纬度

# 创建 SpatialPoints 对象
coordinates(locations) <- ~ gridx + gridy

# 获取所有 TIFF 文件的路径
tif_files <- list.files("D:\\data\\min\\minbd", pattern = "\\.tif$", full.names = TRUE)

# 遍历每个 TIFF 文件
for (tif_file_path in tif_files) {
  # 读取 TIFF 文件
  tif_file <- raster(tif_file_path)
  
  # 打印文件名
  print(paste("Processing:", tif_file_path))
  
  # 提取第一个波段
  band1 <- tif_file[[1]]
  
  # 提取每个点的温度值,使用 buffer 参数
  temperature_values <- extract(band1, locations, buffer = 1000)  # 使用 1000 米的缓冲区
  
  # 获取文件名中的数字作为列名
  file_name <- basename(tif_file_path)  # 获取文件名
  column_name <- gsub("\\D", "", file_name)  # 提取文件名中的数字
  
  # 创建一个新的列来存储平均温度
  average_temperatures <- numeric(nrow(locations))  # 初始化新列
  
  # 查看提取的温度值
  for (i in 1:nrow(locations)) {
    temp_values <- temperature_values[[i]]
    
    # 将字符型向量转换为数值型
    temp_values_numeric <- as.numeric(temp_values)
    
    # 计算平均值
    average_temperature <- mean(temp_values_numeric, na.rm = TRUE)  # na.rm = TRUE 用于忽略 NA 值
    
    # 将平均温度存储到新的列中
    average_temperatures[i] <- average_temperature
  }
  
  # 将提取的温度值添加到 locations 数据框中
  locations[[column_name]] <- average_temperatures
}

# 将更新后的数据框写入新的 CSV 文件
write.csv(locations, "D:\\data\\min\\minwd.csv", row.names = FALSE)
# 提示完成
print("Average temperatures have been added to the CSV file.")

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐