Using two grouping designations to create one 'combined' grouping variable

前端 未结 4 1796
粉色の甜心
粉色の甜心 2021-01-20 01:18

Given a data.frame:

df <- data.frame(grp1 = c(1,1,1,2,2,2,3,3,3,4,4,4),
                 grp2 = c(1,2,3,3,4,5,6,7,8,6,9,10))

#> df
#   grp1 grp2
#1            


        
4条回答
  •  一个人的身影
    2021-01-20 01:32

    Based on https://stackoverflow.com/a/35773701/2152245, I used a different implementation of igraph because I already had an adjacency matrix of sf polygons from st_intersects():

    library(igraph)
    library(sf)
    # Use example data
    nc <- st_read(system.file("shape/nc.shp", package="sf"))
    nc <- nc[-sample(1:nrow(nc),nrow(nc)*.75),] #drop some polygons
    # Find intersetions
    b <- st_intersects(nc, sparse = F)
    g  <- graph.adjacency(b)
    clu <- components(g)
    gr <- groups(clu)
    # Quick loop to assign the groups
    for(i in 1:nrow(nc)){
        for(j in 1:length(gr)){
          if(i %in% gr[[j]]){
            nc[i,'group'] <- j
          }
        }
      }
    # Make a new sfc object
    nc_un <- group_by(nc, group) %>% 
        summarize(BIR74 = mean(BIR74), do_union = TRUE)
    plot(nc_un['BIR74'])
    

提交回复
热议问题