【问题标题】:Is it possible to create a stars object in R that is the minimum values of two other stars objects?是否可以在 R 中创建一个星星对象,它是其他两个星星对象的最小值?
【发布时间】:2021-11-13 17:06:04
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 请提供一些额外的细节:每个 tif 文件都有一个或多个波段?如果他们有多个乐队,您想要特定乐队或所有乐队的“结果”星对象吗?
  • 嗨@lovalery,每个 tif 只有一个波段,因此生成的对象仅适用于该波段。

标签: r r-stars


【解决方案1】:

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

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 package (v2.0.1) 于 2021-09-20 创建

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

【讨论】:

  • 嗨@Ben Lee,我的回答最终解决了你的问题吗?如果是这样,请将其标记为已接受,以便其他用户更容易找到正确的答案。如果您不这样做,请写出问题所在。
  • 嗨@lovalery,这正是我想要的!非常感谢您的帮助!
  • 嗨@Ben Lee,感谢您验证答案,很高兴能为您提供帮助。祝你一切顺利。
猜你喜欢
  • 2021-12-07
  • 2021-06-21
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多