R function with dynamic input range

functions

#1

My data has the following input variables

value- 20,30,50
var1 - 6.5,4,3.2
var2 - 0.6,1.1,0.9

(number of data points are dynamic with each iteration, it could range from 3 to 6)

structure below:

|value|20|30|50|
|var 1|6.5|4|3.2|
|var 2|0.6|1.1|0.9|

I basically need to create a function that takes these variables as dynamic inputs and perform certain arithmetic operations and give a final result as 1 single value.
The catch here is the arithmetic operations can take only 2 values at one time.

For the case above, below is the sample operation:

grp1_value = (20*6.5)+log(0.6) + (30*4)+log(1.1)
grp1_var1 = exp(20*6.5)+exp(30*4)
grp1_var2 = exp(20*0.6)+exp(30*1.1)

grp2= ( 50*3.2)+log(0.9) + (grp1_value * grp1_var1)+log(grp1_var2)

grp2 value should be my output

If my data has more than 3 entries, i should keep doing the operations taking 2 arguments each time.

Any suggestions on the most effective way to write a R function for this case?


#2

The logical equation for grp2 doesn't match with grp1_value. Do you want to append value & var_1 or multiply them?

Thanks!
Heramb


#3

i want to multiply them


#4
v1 = c(20, 30, 50) 
v2 = c(6.5, 4, 3.2) 
v3 = c(0.6, 1.1, 0.9)

ref_v1 <- NULL
ref_v2 <- NULL
ref_v3 <- NULL

n <- length(v1)
cond <- 1

while((cond + 1) <= n){
  if(cond == 1){
    out_v1 <- ((v1[1] * v2[1]) + log(v3 [1])) + ((v1[2] * v2[2]) + log(v3[2]))
    out_v2 <- exp(v1[1] * v2[1]) + exp(v1[2] * v2[2])
    out_v3 <- exp(v1[1] * v3[1]) + exp(v1[2] * v3[2])
    
    ref_v1 <- out_v1
    ref_v2 <- out_v2
    ref_v3 <- out_v3
    
    cond <- cond + 1
    
  }else{
    
    out_v1 <- ((v1[cond +1] * v2[cond +1]) + log(v3 [cond +1])) + ((ref_v1 * ref_v2) + log(ref_v3))
    out_v2 <- exp(v1[cond +1] * v2[cond +1]) + exp(ref_v1 * ref_v2)
    out_v3 <- exp(v1[cond +1] * v3[cond +1]) + exp(ref_v1 * ref_v3)
    
    cond <- cond + 1
  }
}

Something like this might work.. There can be more efficient and mature solutions.

Thanks!
Heramb


#5

thanks much. this works