Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205423

Apply different sf functions to groups in a data frame

$
0
0

I'm trying to calculate different Euclidean buffers (one 400m and one 800m) within a single simple features data frame using a set of piped dplyr function calls. The buffer distance should be specified for each feature based on the value of a grouping variable. I could easily split the data frame based on known values of the grouping variable, but I'd like to make the method as general as possible.

The following code works, but obviously only returns a single 400m buffer for all groups:

library(sf)
library(dplyr)

set.seed(42)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc$grp <- sample(c(0,1), replace = TRUE, size = 100)

nc_buff <- nc %>%
  group_by(grp) %>%
  st_transform(32119) %>%
  group_map(~ st_buffer(.x, 400))

Ideally I'd split the data frame, calculate each buffer, and return a single simple features data frame with both sets of buffers combined.

How can I return a single data frame that contains a 400m buffer for grp == 0 and an 800m buffer for grp == 1?


Viewing all articles
Browse latest Browse all 205423

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>