npar.deriv <- function(filename,ages,birth.year){ ################################################################################################################# # Author: Daniela Kuruczova # # Purpose: Nonparametric mortality curve fitting via smoothing splines 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: list with items: "country": Country name # # "ss.males": smoothing spline approximation of the male mortality curve # # "deriv.males": first derivative of the male mortality curve # # "ss.females": smoothing spline approximation of the female mortality curve # # "deriv.females": first derivative of the female mortality curve # # Example of use: npar.deriv("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) age.new <- seq(min(ages),max(ages),length=200) dy.M <- predict(s.M, data.frame(Age=age.new), deriv = 1) dy.F <- predict(s.F, data.frame(Age=age.new), deriv = 1) s.M <- predict(s.M, data.frame(Age=age.new), deriv = 0) s.F <- predict(s.F, data.frame(Age=age.new), deriv = 0) output <- list(country=country.name,ss.males = s.M,deriv.males = dy.M, ss.females=s.F, deriv.females = dy.F) return(output) }