Reputation: 43
Let's say I have a data frame with spatial columns (x,y), a time column (time), and a data column (value). How can I correctly coerce this to a stars object using st_as_stars
?
df <- expand_grid(time=1:10,
x=1:10,
y=1:10)
df$value <- 1:1000
This is the original order of the data frame:
> head(df)
# A tibble: 6 x 4
time x y value
<int> <int> <int> <int>
1 1 1 1 1
2 1 1 2 2
3 1 1 3 3
4 1 1 4 4
5 1 1 5 5
6 1 1 6 6
Something is incorrectly specified here when I try to cast the data frame to a stars
object:
s <- st_as_stars(df,
dimensions=st_dimensions(time=sort(unique(df$time)),
x=sort(unique(df$x)),
y=sort(unique(df$y)),
point=TRUE),
dims=c('time','x','y'))
This stars object has problems. (1) The 'y' column was taken as an attribute.
> s
stars object with 3 dimensions and 2 attributes
attribute(s):
y value
Min. : 1.0 Min. : 1.0
1st Qu.: 3.0 1st Qu.: 250.8
Median : 5.5 Median : 500.5
Mean : 5.5 Mean : 500.5
3rd Qu.: 8.0 3rd Qu.: 750.2
Max. :10.0 Max. :1000.0
dimension(s):
from to offset delta refsys point values x/y
time 1 10 0.5 1 NA NA NULL [x]
x 1 10 10.5 -1 NA NA NULL [y]
y 1 10 0.5 1 NA NA NULL
And (2) casting the stars object back to a data frame shows that the data 'value' in not ordered as in the original data frame.
> head(as.data.frame(s))
time x y y.1 value
1 1 10 0.5 1 91
2 2 10 0.5 1 191
3 3 10 0.5 1 291
4 4 10 0.5 1 391
5 5 10 0.5 1 491
6 6 10 0.5 1 591
How can I correctly cast the data frame back and forth to a stars
object?
The stars
object and methods are extremely useful, but I am puzzled why I can't work out this seemingly simple data conversion. Any help would be greatly appreciated.
Upvotes: 4
Views: 956
Reputation: 4121
Have you tried
st_as_stars(df, dims = c("x", "y", "time"))
?
Upvotes: 4