Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a value when comparing two columns for the max value in R

Tags:

r

max

I have two columns: A and B, with values from 1 to 7 each. I need to get the maximum value between both columns EXCLUDING the value 7, how can I do that? OR In the case that A has 7 I keep the value of B, this would serve me more, for instance:

A <- c(1,1,1,3,2,4,2,5,6,7)
B <- c(7,3,6,7,4,1,6,7,3,4)
df <- data.frame(A, B)

Expected results: 1,3,6,3,4,4,6,5,6,4 
like image 445
AgusDam87 Avatar asked Dec 10 '22 23:12

AgusDam87


1 Answers

One option could be:

with(df, pmax(A * (A != 7), B * (B != 7)))

 [1] 1 3 6 3 4 4 6 5 6 4

To deal with missing values:

with(df, pmax(A * (A != 7), B * (B != 7), na.rm = TRUE))

Considering also negative values:

with(df, pmax(A * (A != 7)^NA, B * (B != 7)^NA, na.rm = TRUE))
like image 169
tmfmnk Avatar answered Apr 07 '23 09:04

tmfmnk