Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate row specific based on min

Tags:

r

My data looks like this

df <- data.frame(x = c(3, 5, 4, 4, 3, 2),
                 y = c(.9, .8, 1, 1.2, .5, .1))

I am trying to multiply each x value by either y or 1, depending on which has the least value.

df$z <- df$x * min(df$y, 1)

The problem is it is taking the min of the whole column, so it is multiplying every x by 0.1.

Instead, I need x multiplied by .9, .8, 1, 1, .5, .1...

like image 341
pyll Avatar asked Dec 21 '25 17:12

pyll


1 Answers

We need pmin that will go through each value of 'y' and get the minimum val when it is compared with the second value (which is recycled)

pmin(df$y, 1)
#[1] 0.9 0.8 1.0 1.0 0.5 0.1

Likewise, we can have n arguments (as the parameter is ...)

pmin(df$y, 1, 0)
#[1] 0 0 0 0 0 0

To get the output, just multiply 'x' with the pmin output

df$x * pmin(df$y, 1)

which can also be written as

with(df, x * pmin(y, 1))
like image 196
akrun Avatar answered Dec 23 '25 06:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!