[R] Solve system of non linear equations using nasted loops
Santiago Burone
santiagoburone at icloud.com
Wed May 10 20:20:29 CEST 2017
Hello,
I'm new at R and I would like to use it in order to solve a system of non linear equations. I have the code that works but im not able to save the results.
My system has three equations and i would like to solve this using three nested loops, becouse i need solutions for all the values combinations.
The code im using is this:
library(nleqslv)
#x3 es gamma
#x2 es alpha
#x1 es beta
MA <- c(50000, 43600, 40000, 38800, 37600, 34400, 31600, 27200, 24400, 20000)
MI <- c(10000, 21800, 20000, 19400, 18800, 17200, 15800, 13600, 12200, 10000)
ME <- c(30000, 32700, 30000, 29100, 28200, 25800, 23700, 20400, 18300, 15000)
DE <- c(0.384900179, 0.19245009, 0.19245009, 0.19245009, 0.19245009, 0.19245009, 0.19245009, 0.19245009, 0.19245009, 0.19245009)
for (i in 1:9) {
for (j in 1:9){
for (k in 1:9){
df.names <- paste("SociedadB",1:10,sep="")
fun <- function(x) {
f <- numeric(length(x)) # read as:
f[1] <- 1*x[3] - (log(ME[1+i]/ME[1])+(1*x[1]+1*x[2])*(2)*(log((MA[1]-ME[1])/(MA[i+1]-ME[i+1]))))/(log(0.19245009/0.384900179))
f[2] <- 1*x[3] - (log(MI[1+j]/MI[1])-(1*x[2])*(2)*(log((MA[1+j]-MI[1+j])/(MA[1]-MI[1]))))/(log(0.19245009/0.384900179))
f[3] <- 1*x[3] - (log(MA[1+k]/MA[1])-(1*x[1])*(2)*(log((MI[1+k]-MA[1+k])/(MI[1]-MA[1]))))/(log(0.19245009/0.384900179))
f
}
startx <- c(1,1,1)
answers<-as.data.frame(nleqslv(startx,fun))
d.frame <- (answers$x)
assign(df.names[k+20], d.frame)
despejes<- data.frame(SociedadB2, SociedadB3, SociedadB4, SociedadB5, SociedadB6, SociedadB7, SociedadB8, SociedadB9, SociedadB10)
}
}
}
despejes<- data.frame(SociedadB2, SociedadB3, SociedadB4, SociedadB5, SociedadB6, SociedadB7, SociedadB8, SociedadB9, SociedadB10)
If im not wrong i should have 1000 different solutions but the data frame only save 10 results. I tried copying the last part of the code between the last two brackets (changing the name of the data frame despejes for despejes 1, 2 and 3 but i only get three data frames with exactly the same results. I dont know how could i save all the results of every combination. I mean, i need to solve for i=1, j=1 and the 9 diferent values of k and save those results, then i=1, j=2 and the 9 values of k..
I know this might be a easy question but i have not been able to find a solution in the last days.
Thanks in advance if you can help me.
Santiago.
[[alternative HTML version deleted]]
More information about the R-help
mailing list