Skip to content
Prev 23617 / 29559 Next

Programmatically convert raster stack in data frame based on polygon extraction

Hi Thiago,

extract() and some dataframe manipulation should do the trick. See 
comments in line.

Cheers,
Lo?c
On 10/29/2015 09:06 PM, Thiago V. dos Santos wrote:
Cool project
# additional packages for dataframes manipulation
library(dplyr)
library(tidyr)
# Extract values for all polygons
spdf <- raster::extract(days.above.10, locs, fun = median, na.rm = TRUE, 
sp = TRUE)

# There is also a df = TRUE option in extract, but it returns only the 
extracted raster values, without binding them with the 
spatialpolygondataframe attributes. I think

# Get dataframe out of spdf
df <- spdf at data

df1 <- select(df, NAME, Jan.2010:Dec.2010)
df2 <- gather(df1, period, freq, -NAME)
df3 <- separate(df2, period, into = c('month', 'year'))
# Can you add these columns "manually" or does it need to be automated?
df3$variable <- 'temperature'
df3$cut <- 10

# If you do the same for cut == 15, etc, you can then rbind() them