Justas Mundeikis
Justas Mundeikis

Reputation: 995

R function values to dataframe

I'm building this function

f <- function(x) {
        bruto <- x*1.289
        LC <- bruto*1.0124
        npd <- max(470 - 0.16*max(0,(bruto - 600)),0)
        lubos <- 5*850*1.289*1.05^3
        tax_base <- max(0,(bruto-npd))
        gpm <- ifelse(bruto<=lubos, tax_base*0.21, lubos *0.21+(bruto-lubos)*0.25) 
        sodra <- min(max(bruto*0.185, 600*0.185), lubos * 0.185)
        db <- bruto*0.0124
        neto <- bruto - gpm - sodra
        list(old_bruto=x, new_bruto=bruto, npd=npd, gpm = gpm, sodra = sodra, neto = neto, ITR=((LC-neto)/LC))
}

If I enter single values like f(400) etc, it gives the right results, but if I try

x <- seq(100, 25000, by=10)
df <- f(x)
df <- data.frame(old_bruto=df$old_bruto, ITR=df$ITR)

It gives me very weird results example f(100) should result in ITR=0.86, but in df ITR(100)=20.99

Could somebody point ou, where I do the mistake? Thanks!

Upvotes: 0

Views: 33

Answers (1)

r2evans
r2evans

Reputation: 160437

One problem perhaps is that you are using min and max, which will return only one number. When you vectorize things, you need them to return the piece-wise max of vectors.

Enter pmin and pmax:

min(1:5, 3)
# [1] 1
pmin(1:5, 3)
# [1] 1 2 3 3 3

Try this version instead:

f <- function(x) {
        bruto <- x*1.289
        LC <- bruto*1.0124
        npd <- pmax(470 - 0.16*pmax(0,(bruto - 600)),0)
        lubos <- 5*850*1.289*1.05^3
        tax_base <- max(0,(bruto-npd))
        gpm <- ifelse(bruto<=lubos, tax_base*0.21, lubos *0.21+(bruto-lubos)*0.25) 
        sodra <- pmin(pmax(bruto*0.185, 600*0.185), lubos * 0.185)
        db <- bruto*0.0124
        neto <- bruto - gpm - sodra
        list(old_bruto=x, new_bruto=bruto, npd=npd, gpm = gpm, sodra = sodra, neto = neto, ITR=((LC-neto)/LC))
}

f(c(100,101))
# $old_bruto
# [1] 100 101
# $new_bruto
# [1] 128.900 130.189
# $npd
# [1] 470 470
# $gpm
# [1] 0 0
# $sodra
# [1] 111 111
# $neto
# [1] 17.900 19.189
# $ITR
# [1] 0.8628335 0.8544119

Upvotes: 1

Related Questions