


cond.moments <- function(df,env) {

ee <- df[,mean(ng),by=c("agroup","pc")]
setkeyv(ee,c("agroup","pc"))

ff <- df[,sd(ng),by=c("agroup","pc")]

setkeyv(df,c("agroup","pc"))
setkeyv(ee,c("agroup","pc"))
ee$condmean <- ee$V1
ee$V1 <- NULL
dfo <- merge(df,ee)

setkeyv(ff,c("agroup","pc"))
ff$condsd <- ff$V1
ff$V1 <- NULL
dfo <- merge(dfo,ff)

dfo$skew <- ((dfo$ng - dfo$condmean)/dfo$condsd)^3
dfo$kurt <- ((dfo$ng - dfo$condmean)/dfo$condsd)^4

gg <- dfo[,mean(skew),by=c("agroup","pc")]
setkeyv(gg,c("agroup","pc"))

hh <- dfo[,mean(kurt),by=c("agroup","pc")]
setkeyv(hh,c("agroup","pc"))

ii <- df[,list(p025=quantile(ng,0.025),p10=quantile(ng,0.1),
                p25=quantile(ng,0.25),p50=quantile(ng,0.5),p75=quantile(ng,0.75),
                p90=quantile(ng,0.9),p975=quantile(ng,0.975)),by=c("agroup","pc")]

ii$p9010 <- ii$p90-ii$p10
ii$kelley <- ((ii$p90-ii$p50)-(ii$p50-ii$p10))/(ii$p90-ii$p10)
ii$kelleynum <- (ii$p90-ii$p50)
ii$kelleyden <- (ii$p50-ii$p10)
ii$crowsid <- (ii$p975-ii$p025)/(ii$p75-ii$p25)

env$cmean <- ee
env$csd <- ff
env$cskew <- gg
env$ckurt <- hh
env$ii <- ii

}

gen.agroups <- function(df,groups) {
  
  df$agroup <- NULL
  
  if (groups==1) {
  
  df$agroup=0
  df$agroup[df$Age<25] <- 1
  df$agroup[df$Age>24 & df$Age<30] <- 2
  df$agroup[df$Age>29 & df$Age<35] <- 3
  df$agroup[df$Age>34 & df$Age<40] <- 4
  df$agroup[df$Age>39 & df$Age<45] <- 5
  df$agroup[df$Age>44 & df$Age<50] <- 6
  df$agroup[df$Age>49 & df$Age<55] <- 7
  df$agroup[df$Age>54 & df$Age<60] <- 8
   df$agroup[df$Age>59] <- 9
   
   
   df$agroup <- as.factor(df$agroup)
   df$agroup <- mapvalues(df$agroup,from=seq(1,9),
                          to=c("20-24","25-30","31-35","36-40","41-45",
                               "46-50","51-55","56-60","61-65"))
   
    
  } else if (groups==2) {

  df$agroup <- 0
  df$agroup[df$Age<35] <- 1
  df$agroup[df$Age>34 & df$Age<50] <- 2
  df$agroup[df$Age>49 & df$Age<61] <- 3
  
  df <- subset(df,agroup>0)
  
  
  df$agroup <- as.factor(df$agroup)
  df$agroup <- mapvalues(df$agroup,from=seq(1,3),
                         to=c("25-34","35-49","50-60"))

  }
  
  
  return(df)

}

uncond.moments <- function(df,env,min.age) {

aa <- df[,mean(ry),by=Age]
setkeyv(aa,"Age")

bb <- df[,sd(ry),by=Age]
setkeyv(bb,"Age")

df$skew <- ((df$ry - aa$V1[df$Age-min.age+1])/bb$V1[df$Age-min.age+1])^3

cc <- df[,mean(skew),by=Age]

df$kurt <- ((df$ry - aa$V1[df$Age-min.age+1])/bb$V1[df$Age-min.age+1])^4

dd <- df[,mean(kurt),by=Age]

env$umean <- aa
env$usd <- bb
env$uskew <- cc
env$ukurt <- dd

}