4

So I have a dataframe that looks like this:

      x     y  band   val
  <dbl> <dbl> <int> <dbl>
1  12.5  48.7     1     0
2  14.3  47.3     1     0
3  10.3  48.0     1     0
4  13.6  46.7     1     0
5  12.4  48.5     1     0
6  14.5  47.6     1     0

In the band column are four bands (red, green, blue and alpha). What I would like to do is to convert it to a stars object with the bands column being a dimension and the val column an attribute. I simply cant figure out how to do that.

st_as_stars(df) gives me that:

stars object with 2 dimensions and 2 attributes
attribute(s):
      Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
band     1    1.75    2.5  2.5    3.25    4 1480
val      0    0.00    0.0  0.0    0.00    0 1480
dimension(s):
  from to offset delta refsys point                                      values x/y
x    1 40     NA    NA     NA    NA [9.554126,9.569126),...,[17.02663,17.04663) [x]
y    1 38     NA    NA     NA    NA [49.00454,48.94454),...,[46.73454,46.60454) [y]

But I do not know how to bring the attribute back to a dimension...

Here is a sample dataset:)

structure(list(x = c(12.536626, 14.256626, 10.316626, 13.566626, 
12.401626, 14.506626, 13.026626, 15.946626, 10.911626, 9.576626, 
13.046626, 12.146626, 11.461626, 9.891626, 14.846626, 14.626626, 
10.226626, 16.631626, 12.616626, 16.881626, 13.251626, 14.246626, 
9.561626, 10.366626, 13.326626, 10.261626, 12.441626, 13.526626, 
16.146626, 17.036626, 13.636626, 15.751626, 17.016626, 13.956626, 
13.141626, 13.606626, 13.136626, 12.726626, 15.596626, 10.891626
), y = c(48.7045384, 47.2595384, 47.9645384, 46.6695384, 48.4945384, 
47.5895384, 48.7395384, 46.8445384, 47.0095384, 47.8445384, 48.7695384, 
46.8695384, 48.0645384, 48.6495384, 47.0195384, 48.7595384, 46.7995384, 
48.0545384, 46.7995384, 47.5645384, 46.9495384, 47.0295384, 48.9745384, 
47.7195384, 47.0345384, 47.6595384, 47.7095384, 47.1495384, 47.3995384, 
48.5995384, 47.0095384, 48.5845384, 47.5795384, 47.1745384, 48.8595384, 
47.1395384, 47.7745384, 47.4095384, 47.3795384, 48.9145384), 
    band = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
    3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), val = c(0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
    0)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-40L))

1 Answer 1

1

The key is the dims argument

data$band = c("red", "blue", "green", "alpha")[data$band]
r <- st_as_stars(data, dims = c("x", "y", "band"))

See also https://stackoverflow.com/questions/67641493/how-can-i-cast-a-data-frame-to-a-stars-object-with-a-time-dimension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.