Is there any way to do a max if function in R? I am trying to clean up data by summarizing it and only pulling out information where it occurs the most instance. In Excel I would use MAX(IF for this. Is there any way to do the same thing in R?
            Asked
            
        
        
            Active
            
        
            Viewed 6,039 times
        
    -2
            
            
        - 
                    3Could you give a minimal example for that with the desired output?! – Cleb Jul 29 '15 at 16:10
- 
                    3Please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. – MrFlick Jul 29 '15 at 16:13
- 
                    I would try the following scheme: `ifelse(test=what_you_want_to_check, yes=max(some_data),no=something_else_happening)` – MaZe Jul 29 '15 at 16:24
1 Answers
3
            
            
        As I understand it, MAX(IF(C2:C8=C11, D2:D8)) in Excel would basically take the maximum value of the D cells for the condition C2:C8=C11 holds true. This is a one-liner in R:
# Some data
x <- c(1, 1, 2, 2, 3, 3)
y <- c(10, 20, 30, 40, 50, 60)
# Maximum y value where x equals 2
max(y[x == 2])
# [1] 40
This code returns the maximum y value assuming the corresponding x value is equal to 2.
 
    
    
        josliber
        
- 43,891
- 12
- 98
- 133
