0

我有两个作为 tif 读入 R 的星星对象:

tif1 <- stars::read_stars("/data.tif")
tif2 <- stars::read_stars("/data2.tif")

它们覆盖相同的范围并具有相同的分辨率。我知道我可以用对象做代数——例如,要创建一个新对象,它是前两个值的平均值,我可以使用:

tif.avg <- (tif1 + tif2)/2

但是,我想知道是否可以创建一个从它们中提取最小值的新对象。我已经尝试了几种不同的方法,但我已经用这个碰到了一堵砖墙。有人知道这是否可能吗?

4

1 回答 1

0

好的,感谢@Ben Lee 的澄清。因此,作为您评论的后续行动,请在下面(参见 Reprex)找到您的问题的一种解决方案:

代表:

library(raster)
#> Le chargement a nécessité le package : sp
library(stars)
#> Le chargement a nécessité le package : abind
#> Le chargement a nécessité le package : sf
#> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1


# 1. Creating two stars objects
r1 <- raster(ncols = 3, nrows = 3)
values(r1) <- seq(length(r1))

r2 <- raster(ncols = 3, nrows = 3)
values(r2) <- rev(seq(length(r2)))

r_stack <- stack(r1, r2)
writeRaster(r_stack, "raster.tif", 
            bylayer = TRUE, suffix = 1:nlayers(r_stack))

tif1 <- read_stars("raster_1.tif")
tif2 <- read_stars("raster_2.tif")

# Array of the first stars object
tif1[[1]]
#>      [,1] [,2] [,3]
#> [1,]    1    4    7
#> [2,]    2    5    8
#> [3,]    3    6    9

# Array of the second stars object
tif2[[1]]
#>      [,1] [,2] [,3]
#> [1,]    9    6    3
#> [2,]    8    5    2
#> [3,]    7    4    1



# 2. Creating a 'stars' object with the minimum values
# of the two previous stars objects

# 2.1. retrieving the min values between the two stars object 
tif_min <- pmin(tif1[[1]], tif2[[1]])

# 2.2. converting the resulting array 'tif_min' into a stars object
tif_min <- st_as_stars(tif_min)

# 2.3. retrieving the dimensions from one of the two previous
# stars object (here, tif1) and setting a name
st_dimensions(tif_min) <- st_dimensions(tif1)
setNames(tif_min, "tif_min")

#> stars object with 2 dimensions and 1 attribute
#> attribute(s):
#>          Min. 1st Qu. Median     Mean 3rd Qu. Max.
#> tif_min     1       2      3 2.777778       4    5
#> dimension(s):
#>   from to offset delta refsys point values x/y
#> x    1  3   -180   120 WGS 84 FALSE   NULL [x]
#> y    1  3     90   -60 WGS 84 FALSE   NULL [y]

# 2.4 a little check!
tif_min[[1]]
#>      [,1] [,2] [,3]
#> [1,]    1    4    3
#> [2,]    2    5    2
#> [3,]    3    4    1
#>These are the minimum values of the two "star" input objects

reprex 包于 2021-09-20 创建(v2.0.1)

请确认这是您要查找的内容(如果是,请不要忘记验证答案,以便其他用户更容易找到此解决方案)

于 2021-09-20T14:00:58.900 回答