nested ifelse calculations in R -
i relatively new r , finding nested ifelse functionality not behave expect. begin, info used input function:
loss_cor_df<-data.frame(from_1=c(0,.4,0), to_1=c(0,.5,0), from_2=c(0,.55,0), to_2=c(0,.65,0), from_3=c(0,.75,0), to_3=c(0,.85,0) ) loss_cor_dol<-100*loss_cor_df loss_cor_rate_df<-data.frame(rate_1=c(0,0.5,0), rate_2=c(0,0.75,0), rate_3=c(0,1,0))
my function:
apply_lc<- function(x, lc, rate) {ifelse(x>=lc$from_3, -rate$rate_1*(min(x,lc$to_1) - lc$from_1) - rate$rate_2*(min(x,lc$to_2)-lc$from_2) - rate$rate_3*(min(x,lc$to_3)-lc$from_3), ifelse(x>=lc$from_2, -rate$rate_1*(min(x,lc$to_1) - lc$from_1) - rate$rate_2*(min(x,lc$to_2)-lc$from_2), ifelse(x>=lc$from_1, -rate$rate_1*(min(x,lc$to_1) - lc$from_1), 0))) }
if apply scalar, expected result.
> apply_lc(85,loss_cor_dol[2,], loss_cor_rate_df[2,]) [1] -22.5
however, when attempt following, no longer correct answer.
> apply_lc(c(85,80),loss_cor_dol[2,], loss_cor_rate_df[2,]) [1] -17.5 -17.5
i able use loops , "other" if...else function. however, performance reasons hoping vectorize operation. "apply" family did not seem work inputs function may vary every column in data. suspect have fundamental misunderstanding way in r interprets information , appreciate asssitance.
Comments
Post a Comment