Re: [R] Group close numbers in a vector

From: Robert Baer <rbaer_at_atsu.edu>
Date: Sat, 21 May 2011 13:16:25 -0500

> 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

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat 21 May 2011 - 18:18:07 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 21 May 2011 - 23:00:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive