Skip to content

stars objects and case_when

3 messages · Edzer Pebesma, Julian Burgos

#
Dear list,

I am wondering if there is a way to use logical statements to replace values of a stars object, for example the case_when function or some other "tidyverse friendly" approach.  For example, I can do something like this:

st1 <- read_stars(system.file("tif/L7_ETMs.tif", package = "stars")) %>%
  slice(band, 1)

st1[st1 < 100] <- NA
st1[st1 > 100 & st1 < 150] <- 2

... and so for.  But I am wondering if there is a way to do this as part of a pipe, looking something like this:

st1 <- read_stars(system.file("tif/L7_ETMs.tif", package = "stars")) %>%
  slice(band, 1) %>%
  mutate(x <- case_when (x<100 ~ NA,
                         x>100 & x<150 ~ 2))

Any ideas?

Takk,

Julian

--
Julian Mariano Burgos, PhD
Hafranns?knastofnun, ranns?kna- og r??gjafarstofnun hafs og vatna/
Marine and Freshwater Research Institute
Botnsj?varsvi?s / Demersal Division
  Fornub??ir 5, IS-220 Hafnarfj?r?ur, Iceland
www.hafogvatn.is
S?mi/Telephone : +354-5752037
Netfang/Email: julian.burgos at hafogvatn.is
#
Thank you for pointing to this possibility, I'll add it to the stars 
docs somewhere.

This works but only slightly adapted, e.g. as

out = read_stars(system.file("tif/L7_ETMs.tif", package = "stars")) %>%
   slice(band, 1) %>%
   setNames("x") %>%
   mutate(x = case_when (x<100 ~ NA_real_,   x>100 & x<150 ~ 2))

where:
- I uses setNames("x") so that the attribute is renamed to "x", and you 
can use x in the case_when expressions (rather than the lengthy 
"L7_ETMs.tif")
- I chnaged NA into NA_real_ : the first RHS of the formulas need to be 
all of the same type; as typeof(NA) is "logical", it breaks on the 
second RHS which returns a numeric; if you would TRUE or FALSE rather 
than 2 in the second case_when formula, using NA would be the right 
thing to do in the first.

The examples of case_when document the need for typed NA in RHS: this is 
intended behavior.
On 9/14/20 4:39 PM, Julian M. Burgos wrote:

  
    
#
Thanks Edzer, I missed that the file name becomes the name of the layer.  This works great.

I should say that I am enjoying converting my raster processing algorithms into the stars package.  It is nice to use tidyverse- and sf-friendly tools.  Thank you (and all your collaborators) for these tools.

My best,

Julian


Edzer Pebesma writes:
--
Julian Mariano Burgos, PhD
Hafranns?knastofnun, ranns?kna- og r??gjafarstofnun hafs og vatna/
Marine and Freshwater Research Institute
Botnsj?varsvi?s / Demersal Division
  Fornub??ir 5, IS-220 Hafnarfj?r?ur, Iceland
www.hafogvatn.is
S?mi/Telephone : +354-5752037
Netfang/Email: julian.burgos at hafogvatn.is