library(dplyr)
library(ggplot2)

Load the grids dataset

grids <- readRDS("~/Dropbox/wombat/outputData/grids/grids.rds")
head(grids)
##   gwn gwc year grid_id group_id  group population_density nightlight
## 1 700 AFG 1992     246    14000 Tajiks                 NA          0
## 2 700 AFG 1992     247    14000 Tajiks           7.705740          0
## 3 700 AFG 1992     248    14000 Tajiks           7.683218          0
## 4 700 AFG 1992     249    14000 Tajiks           7.754266          0
## 5 700 AFG 1992     250    14000 Tajiks           7.729330          0
## 6 700 AFG 1992     251    14000 Tajiks           7.548891          0

Subset by country

country = "AFG"

grid_subset <- grids %>%
  filter(gwc == country) 

Calculate group means

group_means <- grid_subset %>%
  filter(!is.na(population_density)) %>%
  group_by(group, year) %>%
  summarize(nightlight_mean = weighted.mean(nightlight, population_density, na.rm = TRUE))

head(group_means)
## Source: local data frame [6 x 3]
## Groups: group [1]
## 
##   group  year nightlight_mean
##   <chr> <int>           <dbl>
## 1 Aimaq  1992    0.000000e+00
## 2 Aimaq  1993    1.211165e-04
## 3 Aimaq  1994    9.075384e-04
## 4 Aimaq  1995    1.274777e-03
## 5 Aimaq  1996    2.422330e-04
## 6 Aimaq  1997    9.083737e-05

Plot the results

ggplot(group_means, aes(year, nightlight_mean, color=group)) +
  geom_line()