[R] Group close numbers in a vector

jim holtman jholtman at gmail.com
Sun May 22 00:41:35 CEST 2011


Is this what you are after:

> x = c(1 ,2 ,4 ,7 ,9 ,10 ,15)
> # partition if the difference is > 2)
> breaks <- cumsum(c(0, diff(x) > 2))
> # partition into different lists
> split(x, breaks)
$`0`
[1] 1 2 4

$`1`
[1]  7  9 10

$`2`
[1] 15



On Sat, May 21, 2011 at 6:03 PM, Salih Tuna <salihtuna at gmail.com> wrote:
> Hi Robert,
> thanks for your reply. is there a way to store them in separate vectors?
> and when i try it with a different example i got different result. For
> example if x = [1 2 8 9]
> i want the result to be x1 = [1 2] and x2 = [8 9].
> thanks
>
> On Sat, May 21, 2011 at 7:16 PM, Robert Baer <rbaer at atsu.edu> wrote:
>
>> 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
>>
>>
>>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list