2

I have a polygon:

p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)

I create a simple feature polygon object:

library(sf)
poly_sfc <- st_sfc(st_polygon(p1))

and now add a simple dataframe to it:

data <- data.frame(name = "Los Angeles", language = "English", weather ="sunny")
df <- st_sf(data, geometry = poly_sfc)

I can see that it's added the data to the overall sfc.

Simple feature collection with 1 feature and 3 fields
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: -180 ymin: -60 xmax: 10 ymax: 55
epsg (SRID):    NA
proj4string:    NA
         name language weather                       geometry
1 Los Angeles  English   sunny POLYGON ((-180 -20, -140 55...

Now I'd like to rasterise this, which I can using:

library(star)
r <- st_rasterize(df, options = "ALL_TOUCHED=TRUE")

However, when I look at the raster r the data from df has been dropped.

stars object with 2 dimensions and 1 attribute
attribute(s):
      ID        
 Min.   :1      
 1st Qu.:1      
 Median :1      
 Mean   :1      
 3rd Qu.:1      
 Max.   :1      
 NA's   :34597  
dimension(s):
  from  to offset     delta refsys point values    
x    1 328   -180  0.580682     NA    NA   NULL [x]
y    1 199     55 -0.580682     NA    NA   NULL [y]

How can I make sure that the data from df is passed into the raster? Is there a way to do it via st_rasterize ??

Logica
  • 977
  • 4
  • 16
Anthony W
  • 1,289
  • 2
  • 15
  • 28

2 Answers2

0

This seems to be a bug/limitation of stars, which is still only 0.5-6, but here's my work around. The package captures the first numeric column in the dataframe as the value for the raster. So for your example:

data <- data.frame(value = 14, name = "Los Angeles", language = "English", weather ="sunny")

df <- st_sf(data, geometry = poly_sfc)

r <- st_rasterize(df, options = "ALL_TOUCHED=TRUE")
ggplot() + geom_stars(data=r, sf=TRUE)

For character data, the hack would be converting the character to a factor and then back. Hope this helps

Mark R
  • 775
  • 1
  • 8
  • 23
-3

so you start with df made. So to make a raster:

library(raster)
r <- raster(ncol = 180, nrow = 180) # create a base of the raster
extent(r) <- extent(df) # extent the raster to your df
rp <- rasterize(df, r)

And this is the result

enter image description here

K. Peltzer
  • 326
  • 3
  • 7
  • 1
    I dont think that answers the question. I'm trying to capture the dataframe from the sfc into the raster – Anthony W Feb 17 '20 at 15:18