npar.equal <- function(filename,ages,birth.year){ ################################################################################################################# # Author: Daniela Kuruczova # # Purpose: Finding age where male mortality is equivalent to female mortality for # # data downloaded from http://www.mortality.org/ # # Arguments: filename = path and name of file to use as data source # # ages = sequence of ages that will be used for the cohort # # birth year = birth year of the cohort # # Output: data frame with items: "age": female age # # "EQ": male age with mortality equivalent to females with given age # # Example of use: npar.equal("Mx_1x1_Australia.txt",30:60,1954) # # # # 2018/11/21 Initial version (DK) # ################################################################################################################# #Years to extract from data years <- birth.year+ages #Read data file dt <- read.table(filename,header=T,skip=2,na.strings='.') #Replace character + in Age dt$Age <- as.integer(gsub("+", "", as.character(dt$Age),fixed=T)) #Get country name from filename country.name <- substr(filename, 8, regexpr('.txt', filename)[1] - 1) #Filter out data for specified cohort dt.to.use <- dt[dt$Age %in% ages & dt$Year %in% years & dt$Year-dt$Age==birth.year,] #Model calculation lambda <- 0.7 #males s.M <- smooth.spline(dt.to.use$Age, dt.to.use$Male,spar=lambda) #females s.F <- smooth.spline(dt.to.use$Age, dt.to.use$Female,spar=lambda) res.vector <- c() for (i in min(ages):max(ages)){ if(predict(s.M,30)$y<=predict(s.F,i)$y){ temp.f <- function(x){ out <- predict(s.M,x)$y - predict(s.F,i)$y return(out) } res <- uniroot(temp.f,c(min(ages),max(ages))) res.vector <- c(res.vector,res$root) } else{ res.vector <- c(res.vector,NA)} } output <- data.frame(ages=ages,EQ=res.vector) return(output) }