# Combine named list of stars object into one new stars object with the names being a new dimension

I have a list of stars objects that I created in a loop. This little example is more or less replicating my situation.

library(stars)
tif = system.file("tif/lc.tif", package = "stars")
l = list(x,x)
names(l) = c("jan", "feb")

What I would like to have is one stars object with a temporal dimension that has two values: c("jan", "feb").

Now I know there is the generic c-function to combine stars objects and also the merge-function. But I did not manage to use the names of the list-elements as new dimension in the stars object. I don't event know if this is a good idea/approach. But in fact I quite often end up at this point (maybe I'm just doing it wrong all the time) and just wondered if it is easy to collapse a list of stars objects into one stars-object and use the names of the list as a new dimension.

EDIT

I did this:

s = c(do.call("c", l))
merge(s)

And this surprisingly creates the new dimension in the stars object, with as many values as elements in the list. But I'm not really sure if this is the best way...

Your approach is perfectly fine, what's missing is just st_redimension in the final step. This transforms attributes to dimensions while keeping their names:

library(stars)
tif = system.file("tif/lc.tif", package = "stars")
l = list(x,x)
names(l) = c("jan", "feb")
r = do.call("c", l)
r = st_redimension(r)

r
## stars object with 3 dimensions and 1 attribute
## attribute(s):
##  jan.lc.tif.feb.lc.tif
##  Length:7728
##  Class :character
##  Mode  :character
## dimension(s):
##         from to  offset delta                    refsys point                 values x/y
## x          1 84 3092415  3000 Albers Conical Equal Area FALSE                   NULL [x]
## y          1 46   59415 -3000 Albers Conical Equal Area FALSE                   NULL [y]
## new_dim    1  2      NA    NA                        NA    NA jan.lc.tif, feb.lc.tif
• Great, thank you very, very much!!
– Lenn
Commented Jun 22, 2021 at 6:48