Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to group the rows by 200. For example, I want to group up to +200 based on the minimum values into one group. The next group is grouped up to +200 with the next minimum value.

Here is a data set:

data <- data.frame(data = c(10, 110, 1011, 1622, 1822, 2311, 2373, 2388, 6233, 6433))

   data
1   10  
2   110  
3   1011 
4   1622  
5   1822          
6   2311  
7   2373           
8   2388          
9   6233   
10  6433       


data$group <- c(1, 1, 2, 3, 3, 4, 4, 4, 5, 5)

  data     group
1   10       1        #(group: 1, range:10~200)
2   110      1        
3   1011     2        #(group: 2, range:1011~1211)
4   1622     3        #(group: 3, range:1622~1822)
5   1822     3         
6   2311     4        #(group: 4, range:2311~2511) 
7   2373     4         
8   2388     4        
9   6233     5        #(group: 5, range:6233~6433) 
10  6433     5       
question from:https://stackoverflow.com/questions/65650096/how-to-group-by-range-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is a base R option using while loop :

data$group <- NA
group <- 1
min_val <- data$data[1]
next_val <- min_val + 200  
i <- 1

while(i <= nrow(data)) {
  if(data$data[i] > next_val) {
    min_val <- data$data[i]
    next_val <- min_val + 200  
    group <- group + 1
  }
  data$group[i] <- group
  i <- i + 1
}

data
#   data group
#1    10     1
#2   110     1
#3  1011     2
#4  1622     3
#5  1822     3
#6  2311     4
#7  2373     4
#8  2388     4
#9  6233     5
#10 6433     5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...