payments <- matrix(c(2000, 1800, 1500, 1600, 2200, 1600, 1400, 1400, 2500, 2000, 1700, 1600), nrow = 3, ncol = 4,byrow=TRUE) payments eps <- 0.01 chiSquare <- function(riskFactors) { cartype <- c(1,riskFactors[1:2]) #c(chi11,chi12,chi13) age <- riskFactors[3:6] #c(chi21,chi22,chi23,chi24) chiSq <- 0 for (i in 1:3){ for (j in 1:4){ chiSq <- chiSq + (payments[i,j] - cartype[i]*age[j])^2/(cartype[i]*age[j]) } } return(chiSq ) } chiSquare(c(2,2,2,2,2,2)) OptRiskFactors <- optim(c(1,1,1,1,1,1),chiSquare, lower = c(eps ,eps ,eps ,eps ,eps ,eps))$par OptRiskFactors <- c(1,OptRiskFactors) OptRiskFactors tariffs <- matrix(0, nrow = 3, ncol = 4) for (i in 1:3){ for (j in 1:4){ tariffs[i,j] <- OptRiskFactors[i]*OptRiskFactors[3+j] } } tariffs payments totalPayments<-0 totalTariffs<-0 for (i in 1:3){ for (j in 1:4){ totalPayments <- totalPayments + payments[i,j] totalTariffs <- totalTariffs + tariffs[i,j] } } totalPayments totalTariffs