Search code examples
rminimum

How to find a minimum of two columns based on a condition?


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, it should show me the minimum of the combination of Value1 + Value2 (not needed to be within the same row) without exceding 9 as the sum of ID1+ID2.

The result should point me to the combination of x in Value1 and y in Value2, which together are the lowest potential values under the condition that ID1+ID2 are <=9.

Thanks in advance!


Solution

  • One possibility

    library(dplyr)
    goodrow <- filter(df, ID1 + ID2 <= 9) %>% mutate(sumval = Value1 + Value2) %>% filter(sumval == min(sumval))
    

    If I understand well your question, consider using the crossing function. This will compute all the combination of ID1 and ID2

    library(dplyr)
    
    df <- as.data.frame(cbind(ID1,Value1))
    df2 <- as.data.frame(cbind(ID2,Value2))
    df_test <- crossing(df, df2)
    
    
    goodrow <- filter(df_test, ID1 + ID2 <= 9) %>% mutate(sumval = Value1 + Value2) %>% filter(sumval == min(sumval))