library(terra) path1 <- dir('G:/ERA5hr/P/1/',pattern = '*.tif',full.names = T)#导入地址后批量合并 path2 <- dir('G:/ERA5hr/ZUST/1/',pattern = '*.tif',full.names = T) path3 <- dir('G:/ERA5hr/ut_750/1/',pattern = '*.tif',full.names = T) #nc5 <- stack(paths) for (i in 1:length(path1)){ print(path1[i]) p <- stack(path1[i]) zust <- stack(path2[i]) ut <- stack(path3[i]) file_data <- ifelse(zust<ut, 0, (p/9.8)*zust^3*(1-ut/zust)*(1+(ut/zust)^2)) output_path <- paste('G:/ERA5hr/Q/Q750/1/', substr(path1[i],15,28),'.tif',sep='') writeRaster(file_data,output_path, overwrite=TRUE,format = "GTiff") }请修改一下代码
时间: 2024-03-15 12:47:08 浏览: 30
根据您提供的代码,您想要将三个文件夹中的相同位置的多个.tif文件合并为一个新的.tif文件,并进行一些计算,最终输出为新的.tif文件。根据您的需求,我对代码进行了修改,如下所示:
```R
library(terra)
path1 <- dir('G:/ERA5hr/P/1/', pattern = '*.tif', full.names = TRUE)
path2 <- dir('G:/ERA5hr/ZUST/1/', pattern = '*.tif', full.names = TRUE)
path3 <- dir('G:/ERA5hr/ut_750/1/', pattern = '*.tif', full.names = TRUE)
for (i in 1:length(path1)) {
print(path1[i])
# 读取三个.tif文件
p <- rast(path1[i])
zust <- rast(path2[i])
ut <- rast(path3[i])
# 进行计算
file_data <- ifelse(zust < ut, 0, (p / 9.8) * zust ^ 3 * (1 - ut / zust) * (1 + (ut / zust) ^ 2))
# 输出为新的.tif文件
output_path <- paste('G:/ERA5hr/Q/Q750/1/', substr(path1[i], 15, 28), '.tif', sep = '')
writeRaster(file_data, output_path, overwrite = TRUE, format = "GTiff")
}
```
修改后的代码主要进行了以下几个方面的修改:
1. 使用 `rast()` 函数读取.tif文件,而不是使用 `stack()` 函数,因为后者在读取单个文件时会将其转换为三维数组,而我们并不需要这种转换。
2. 将读取的三个.tif文件命名为不同的变量,方便后续的计算。
3. 对每个文件进行计算,并将计算结果赋值给 `file_data` 变量。
4. 使用 `paste()` 函数将输出路径拼接成一个字符串,并将其保存为 `output_path` 变量。
5. 将计算结果写入新的.tif文件中,格式为GTiff,每次覆盖已有文件。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)