Home > Software engineering >  How to find a minimum of two columns based on a condition?
How to find a minimum of two columns based on a condition?

Time:11-15

I have a dataframe in R looking like that

ID1    <- c(1,2,3,4,5,6,7,8,9)
Value1 <- c(2,3,5,2,5,8,17,3,5)
ID2 <- c(1,2,3,4,5,6,7,8,9)
Value2 <- c(4,6,3,5,8,1,2,8,10)

df <- as.data.frame(cbind(ID1,Value1,ID2,Value2))

Now I am searching for the minimum value of the sum of Value1 and Value2 which has a sum of ID1 and ID2 equal or smaller than 9. Thus, the result should show me the row where I have a minimum in Value1 Value2 but without exceding 10 as the sum of ID1 ID2.

Thanks in advance!

CodePudding user response:

For your specific case

which.min(rowSums(df[rowSums(df[,c("ID1","ID2")])<10,c("Value1","Value2")]))

CodePudding user response:

Another one liner,

filter(transform(df, 'new' = df$Value1   df$Value2),(df$ID1   df$ID2 <=9)&(new == min(new)))

CodePudding user response:

One possibility

goodrow <- filter(df, ID1   ID2 <= 9) %>% mutate(sumval = Value1   Value2) %>% filter(sumval == min(sumval))
  • Related