I would like to ask for help with this particular trouble i have. I tried to figure out how to make my code bellow easier and shorter but i haven´t figured it out yet. Could anybody help me to get my function X rid of unnecessary ELSE IF
statements if possible?? LOGIC of function: 1. load input vector (P_Fin) 2. load interest rates 3. each month you multiply less of interest rates, meant as in first year you multiply 1:length(i), second only 2:length("i"), ... so on, last year just the last value of vector "i" HERE is my prototype of function for this but it is too long."
X<-function(){
P_Fin<-c(50,60,70,80,90,100,120,130,130,140,150,170)
axa_dlh<-c(1.02,1.03,1.04,1.02,1.001,1.012,1.017,1.015,1.017,1.031,0.99,1.002)
sum<-0
for(k in 1:12)
{
for(j in 12:1)
{ if(k==1)
{sum<-sum+(P_Fin[k])*(axa_dlh[1])^(j/12)*(axa_dlh[2])*(axa_dlh[3])*(axa_dlh[4])*(axa_dlh[5])*(axa_dlh[6])*(axa_dlh[7])*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==2)
{sum<-sum+(P_Fin[k])*(axa_dlh[2])^(j/12)*(axa_dlh[3])*(axa_dlh[4])*(axa_dlh[5])*(axa_dlh[6])*(axa_dlh[7])*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==3)
{sum<-sum+(P_Fin[k])*(axa_dlh[3])^(j/12)*(axa_dlh[4])*(axa_dlh[5])*(axa_dlh[6])*(axa_dlh[7])*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==4)
{sum<-sum+(P_Fin[k])*(axa_dlh[4])^(j/12)*(axa_dlh[5])*(axa_dlh[6])*(axa_dlh[7])*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==5)
{sum<-sum+(P_Fin[k])*(axa_dlh[5])^(j/12)*(axa_dlh[6])*(axa_dlh[7])*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==6)
{sum<-sum+(P_Fin[k])*(axa_dlh[6])^(j/12)*(axa_dlh[7])*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==7)
{sum<-sum+(P_Fin[k])*(axa_dlh[7])^(j/12)*(axa_dlh[8])*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==8)
{sum<-sum+(P_Fin[k])*(axa_dlh[8])^(j/12)*(axa_dlh[9])*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==9)
{sum<-sum+(P_Fin[k])*(axa_dlh[9])^(j/12)*(axa_dlh[10])*(axa_dlh[11])*(axa_dlh[12])}
else if(k==10)
{sum<-sum+(P_Fin[k])*(axa_dlh[10])^(j/12)*(axa_dlh[11])*(axa_dlh[12])}
else if(k==11)
{sum<-sum+(P_Fin[k])*(axa_dlh[11])^(j/12)*(axa_dlh[12])}
else
{sum<-sum+(P_Fin[k])*(axa_dlh[12])^(j/12)}
}
print(sum) # prints out yearly sum to see if this works
}
}
Aucun commentaire:
Enregistrer un commentaire