William Liu William Liu - 3 years ago 125
R Question

Assign groups based on the trend

I have searched a lot for this simple question, but have not found a solution. It looks really simple. I have a dataframe with a column like this:

Value
0.13
0.35
0.62
0.97
0.24
0.59
0.92
0.16
0.29
0.62
0.98


All values have a range between 0 and 1. What I want is that when the value starts to drop, I assign a new group to it. Within each group, the value is increasing. So the ideal outcome will look like this:

Value Group
0.13 1
0.35 1
0.62 1
0.97 1
0.24 2
0.59 2
0.92 2
0.16 3
0.29 3
0.62 3
0.98 3


Does anyone have a suggestion for how to address this? Thanks!

Answer Source

This isn't the most elegant solution, but it works:

value <- c(0.13, 0.35, 0.62, 0.97, 0.24, 0.59, 0.92, 0.16, 0.29, 0.62, 0.98)

foo <- data.frame(value, group = 1)
current_group <- 1
for(i in 2:nrow(foo)){
  if(foo$value[i] >= foo$value[i-1]){
    foo$group[i] <- current_group
  }else{
    current_group <- current_group + 1
    foo$group[i] <- current_group
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download