Search code examples
rmathematical-optimization

Sorting a vector in R in a specific order


I am solving a constrained optimization problem in R iteratively where the problem if of the following form:

min f(x)

s.t. g(x) < 0

I am doing the optimization iteratively and so I have a variable called f that holds the current value of the function f and vector g of 1's and 0's that tells me if the constraint was met for the ith iteration. To help, here is an example

#Imagine there are 6 time points 
f = c(7,10,6,3,-1,-9)  
g = c(1,1,0,1,1,0)

And so I want to keep track of the best minimum value found at the ith iteration such that the constraint was satisfied. Thus I want to be able to calculate a vector like

h = c(7,7,7,3,-1,-1)

Where h records the minimum value found in time such that the constraint was met. Is there an easy way to do this in R either in loops or not?


Solution

  • Given your f and g, I would do it like this:

    cummin(zoo::na.locf(ifelse(g == 1, f, NA)))
    # [1]  7  7  7  3 -1 -1
    

    Or, perhaps more simply:

    cummin((ifelse(g == 1, f, Inf)))
    # [1]  7  7  7  3 -1 -1