elbersb / segregation

R package to calculate entropy-based segregation indices, with a focus on the Mutual Information Index (M) and Theil’s Information Index (H)
https://elbersb.com/segregation
Other
35 stars 3 forks source link

Error: Cannot compute segregation: the group variable is constant #10

Closed YiyangGao closed 2 years ago

YiyangGao commented 2 years ago

Dear Ben and Matt,

Greetings. I am trying to compute the local segregation score for each racial group by defining schools as groups and races as units. Please find my code below:

library(segregation)
library(tidyverse)
unique_district <- unique(schools00$district)
district_list <- setNames(vector("list", length(unique_district)), unique_district)
race_district <- setNames(lapply(unique_district, function(nm){
  schools00 %>%
    filter(district %in% nm) %>%
    mutual_local(group = "school", unit = "race", weight = "n", wide = TRUE)}), unique_district)

The code above returns with an error "Cannot compute segregation: the group variable is constant". I have checked and checked but did not find any solution to fix the bug. There is definitely variation in schools. If possible, could you please have a look and point out what the problem might be?

Many thanks indeed.

Best, Yiyang

elbersb commented 2 years ago

Hi, the group variable is indeed constant for some districts, try runnign this:

library(segregation)
library(tidyverse)

schools00 %>%
    filter(district == "A5")
#> # A tibble: 5 × 5
#>   state district school race       n
#>   <fct> <fct>    <fct>  <fct>  <dbl>
#> 1 A     A5       A5_1   asian      2
#> 2 A     A5       A5_1   black    268
#> 3 A     A5       A5_1   hisp       3
#> 4 A     A5       A5_1   native     2
#> 5 A     A5       A5_1   white    532

schools00 %>%
    filter(district == "A5") %>%
    mutual_local(group = "school", unit = "race", weight = "n", wide = TRUE)
#> Error in prepare_data(data, group, unit, weight): Cannot compute segregation: the group variable is constant

Created on 2022-01-30 by the reprex package (v2.0.1)