Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ifelse in a dataframe

The data frame that I am using is

> df <- data.frame(Name=c("Joy","Jane","Jack","Jad"),M1=c(10,40,55,90))
> df
  Name M1
1  Joy 10
2 Jane 40
3 Jack 55
4  Jad 90

> df$Final <- ifelse(df$M1<=50,60,max(75,df$M1))
> df
  Name M1 Final
1  Joy 10    60
2 Jane 40    60
3 Jack 55    90
4  Jad 90    90

If the M1 value is less than or equal to 50 then I need 60 as my final value, while if the M1 value is greater than 50 then I need the maximumm(75,M1). In the case of Jack, M1 is 55, so I should get the max(75,55) which is 75. I think it is giving me the max of entire M1 column. How to avoid this?

Desired output

  Name M1 Final
1  Joy 10    60
2 Jane 40    60
3 Jack 55    75
4  Jad 90    90
like image 818
Meesha Avatar asked May 22 '26 03:05

Meesha


1 Answers

You can also use pmax instead of max:

ifelse(df$M1 <= 50, 60, pmax(75, df$M1))

From the help file, pmax takes

one or more vectors (or matrices) as arguments and return(s) a single vector giving the ‘parallel’ maxima ... of the vectors. The first element of the result is the maximum ... of the first elements of all the arguments, the second element of the result is the maximum ... of the second elements of all the arguments and so on.

Thus the third argument to ifelse, the "else" value, is the pairwise maximum of 75 (recycled as many times as needed) and the values of df$M1.

like image 189
lmo Avatar answered May 26 '26 11:05

lmo



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!