Program R: calculate BAL

0

I need to calculate the following:

I have a data frame and I want to create one variable from another one in the following way. The new variable consists of adding all the values of variable 2 as long as they are greater than variable 1. I can not think of any way to do it.

 Caso     Var 1   Var2    Var a calcular
   1      15       25           135
   2      20       30           105
   3      30       45            60
   4      50       60             0
    
asked by Ramiro Oliveri 08.04.2016 в 06:07
source

1 answer

0

One way to solve it:

df=data.frame(Caso=c(1,2,3,4), Var1=c(15,20,30,50), Var2=c(25,30,45,60))

myFun<-function(x){
  return(sum(df$Var2*(df$Var2>x[2] & df$Caso != x[1])))
  cat(x)
}

apply(df, 1, myFun)
[1] 135 130  60   0

Although I think the second calculation of your table should be 130 instead of 105? Since if I understood the logic well, 25 is greater than 20, and every time the elements are added, only the current record is excluded in the sum of the "Var2"

Greetings

    
answered by 17.06.2016 в 21:28