haimen
haimen

Reputation: 2015

Condition to exit a loop in R

I want to write a function to change the median by touching minimum number of elements in my data. My data is as follows,

data = data.frame(name=letters, values = c(0.183487333,0.487690292, 0.510321455,0.616632727, 0.660789818, 0.845322255, 0.867910555, 0.911842909, 0.913312571, 1.017638286, 15.97454546, 16.20765382, 16.27542982, 16.307264, 17.38325527, 17.54139927, 70.08443928, 70.26106764, 75.79405382, 77.72412946, 79.58750724, 84.67373672, 87.04692364, 88.58626037, 94.79392582, 100.0000))
data = data %>% mutate(diff = abs(values - median(values)), rank_diff = dense_rank(diff)) %>% arrange(diff)  

and below is my function,

changemedian <- function(data, increase, rows) 
{
  median2 = median(data$value)
  new_median = median2 + increase
  i = 0
  print(data$name[1:rows])
  data1 = data$values
  while(median2<new_median){
    x = median2
    data1[1:rows] = data1[1:rows] + 0.2
    median2 = median(data1)
    i = i + 0.2
  }
  print(paste("values to be changed per name:",i))
  cat("\n")
  print(paste("New Median that could be achieved:" ,median2))
}

I can call this function when I want to increase the median by 1 and I want to use only 5 values to do it by changemedian(data,1,5). The code is working fine for this. But when I give a improbable condition when the median can't be achieved like changemedian(data,1,1), the loop keeps on running. I want to loop to exit when the median is equal to previous median value. Here when median2 is equal to median2 value during the previous loop, I want to exit the loop by saying "not possible".

I am getting errors to do this. Can anybody help me in doing this?

Thanks

Upvotes: 2

Views: 7463

Answers (1)

R.S.
R.S.

Reputation: 2140

I think what is happening is this -- In case of changemedian(data,1,1), we are only incrementing the first element, which is already greater than the median. So the median does not change on increasing it , and the loop never stops. The median increases only when you increment some numbers smaller than the median.


Edit: To exit the loop if a median is repeated add this line :

if  ( median(data1) == median2 ) break; 

just before the line

median2 = median(data1);

Upvotes: 4

Related Questions