2

I have a rasterbrick clipped from a netCDF file (masked by a shapefile). How can i convert this rasterbrick into a dataframe with columns lat, lon, time and value. I know i can make it using netCDF4 package and expand.grid function there. However i have to create this dataframe on rasterbrick object, not netcdf object.

library(raster)
# Create a rasterStack object with time written to z dimension.
r <- raster(ncol=3, nrow=4)
s <- brick(lapply(1:3, function(x) setValues(r, runif(ncell(r)))))
s<-setZ(s,as.Date('2000-1-1 00:00') + 0:2)

Now from this s how can i get a dataframe df so that df is like

head(df)
    lon  lat          dttm value
1 226.5 54.0 1/1/2000 0:00     2
2 223.5 55.5 1/2/2000 0:00     2
3 225.0 55.5 1/3/2000 0:00     2
4 219.0 57.0 1/4/2000 0:00     2
5 220.5 57.0 1/5/2000 0:00     2
6 222.0 57.0 1/6/2000 0:00     2

. I tried raster to point function.

    raspt<-rasterToPoints(s)
    head(raspt)

However, the data frame is in extended format, i want it in long format because in original data i have more than 50000 layers as hrly data time steps.So basically, i want a long dataframe with x, y, layers as date and value. Thank you for your help.

Lily Nature
  • 613
  • 7
  • 18

1 Answers1

1

You question is more like how to conver data frame from wide to long format. We can use functions from tidyverse to achieve this. In the following example, I added some codes to your original codes. Notice that both dplyr and raster have a select function, so use dplyr::select to avoid confusions. raspt2 is the final output.

library(tidyverse)
library(raster)

# Create a rasterStack object with time written to z dimension.
r <- raster(ncol = 3, nrow = 4)
s <- brick(lapply(1:3, function(x) setValues(r, runif(ncell(r)))))
s <- setZ(s, as.Date('2000-1-1 00:00') + 0:2)

raspt <- rasterToPoints(s)

# Create a data frame showing layer name and time
dt <- data_frame(Layer = names(s), dttm = as.Date(getZ(s)))

# Transform the data
raspt2 <- raspt %>%
  as_data_frame() %>%
  rename(lon = x, lat = y) %>%
  gather(Layer, value, -lon, -lat) %>%
  left_join(dt, by = "Layer") %>%
  dplyr::select(lon, lat, dttm, value)
www
  • 38,575
  • 12
  • 48
  • 84