Q:

How to iteratively change variable value until all predicted probabilities are above .5

I am trying to write code that subtracts a given value from a variable until each row has a predicted probability at or above .05. 
train <- data.frame('cost'= c(120, 3, 2, 4, 10, 110, 200, 43, 1, 51, 22, 14),
                    'price' = c(120, 20, 10, 4, 3, 4, 30, 43, 56, 88, 75, 44),
                    'dich' = c(0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0))

train$dich <- as.factor(train$dich)

test <- data.frame('cost'= c(13, 5, 32, 22, 14, 145, 54, 134, 11, 14, 33, 21),
                   'price' = c(32, 11, 210, 6, 3, 7, 22, 423, 19, 99, 192, 32)
            )

model <- glm(dich ~ cost + price,
             data = train, 
             family = "binomial")

pred  <-   predict(model, test, type = "response")

           1            2            3            4 
3.001821e-01 4.442316e-01 4.507495e-04 6.310900e-01 
           5            6            7            8 
5.995459e-01 9.888085e-01 7.114101e-01 1.606681e-06 
           9           10           11           12 
4.096450e-01 2.590474e-02 9.908167e-04 3.572890e-01

So in the above output the cases 4, 5, 6, and 7 would remain the same because they are already above .05 but for the rest of the cases I would like to subtract 1 from the price column and then run the prediction again and repeat until all cases have a probability at or above .05. 

A:

If you want to subtract 1 for each row (or "customer") individually, rather than 1 across the board:
test$pred_prob <- NA
for (n in 1:nrow(test)) {
  print("-----------------------------")
  print(n)
  while (TRUE) {
    pred <- predict(model, test[n,], type = "response")
    print(pred)
    test$pred_prob[n] <- pred
    if (sum(pred > 0.05) == length(pred)) { 
      print(test$price[n])
      break 
    }
    test$price[n] <- test$price[n] - 1
  }
print(test)
}

# cost price  pred_prob
# 1    13    32 0.30018209
# 2     5    11 0.44423163
# 3    32    96 0.05128337
# 4    22     6 0.63109001
# 5    14     3 0.59954586
# 6   145     7 0.98880854
# 7    54    22 0.71141007
# 8   134   175 0.05074762
# 9    11    19 0.40964501
# 10   14    82 0.05149897
# 11   33    97 0.05081947
# 12   21    32 0.35728897

