[R] Group close numbers in a vector

Robert Baer rbaer at atsu.edu
Sat May 21 20:16:25 CEST 2011


> Hi everyone,
> i am trying to group close numbers in a vector.
> For example i have a vector x = [1 2 4 7 9 10 15].
> I want the code to pick 1 2 4 (max difference between successive numbers 
> is
> 2) and assign them to variable a, then pick 7 9 10 and assign them to b 
> and
> 15 to c. But since i do not know how many groups there will be the code
> should create a,b,c etc as it goes along. So if x = [1 2 4 7 9 10 15 20] 
> it
> should create a,b,c and d this time and assign 20 to d (while the others
> remain the same).

I think the following function should do basically what you want:
codeit = function(x){
  action = c(TRUE, diff(x) <= 2)
  g = paste('x', '1', sep='')
  j = 1
  for (i in 2: length(x)){
    if (action[i-1] != action[i] | action[i] == FALSE) j = j+1
      g[i] = paste('x', j, sep='')
  }
  df = data.frame(x, grp.x=g)
}




------------------------------------------
Robert W. Baer, Ph.D.
Professor of Physiology
Kirksville College of Osteopathic Medicine
A. T. Still University of Health Sciences
800 W. Jefferson St.
Kirksville, MO 63501
660-626-2322
FAX 660-626-2965



More information about the R-help mailing list