0

I have an sf class object, where there are some polygons:

id  use_type   area
1   housing    100
1   farming    200
2   farming    150
2   forest     100
3   housing    250

Polygons with same id value have same geometry. There are also fields use_type and area: first is a name of landuse type within the polygon borders, the second is an area of this landuse type within the polygon borders. So every duplicate geometries containes info about single landuse type, but I want to eliminate duplicates and have this information about landuse types in columns, each representing info about area of a specific landuse type, not different polygons. Like this:

id  housing_area   farming_area   forest_area
1   100            200            NULL
2   NULL           150            100
3   250            NULL           NULL

How can I do this?

  • 1
    It's gonna be hard to answer a question about a very specific data type without a sample of it, unless you really don't need *any* geographic information to do this operation (in which case, it isn't really an sf problem). [See here](https://stackoverflow.com/q/5963269/5325862) on making a reproducible example – camille Dec 24 '21 at 15:53

1 Answers1

1

Yes, as mentioned by camille, it's hard to make this work with geometry since you didn't provide a reproducible example with geometry.

You could separate your data with

tab <- sf::st_drop_geometry( your_sf_object )

Then use dplyr to group and summarize (I'm making the data first):

library(dplyr)
library(sf)

tab <- "id use_type   area
1   housing    100
1   farming    200
2   farming    150
2   forest     100
3   housing    250"

tab <- read.table( text=tab, header=TRUE, 
                   stringsAsFactors = FALSE,
                   colClasses = c( "character", "character", "integer" ))

tab2 <- tab %>%
  group_by(id) %>%
  summarise( housing=sum( area[use_type=="housing"] ),
             farming=sum( area[use_type=="farming"] ),
             forest=sum( area[use_type=="forest"] ) )

> as.data.frame(tab2)
  id housing farming forest
1  1     100     200      0
2  2       0     150    100
3  3     250       0      0

Then take your sf objects's geometry column and join to the data frame (not tested as I don't have your data).

new_sf_object <- left_join( x=tab2, y=your_sf_object$geometry )
Jim Worrall
  • 466
  • 3
  • 11