[R] Appending elements according to criteria to an empty array

Marc Schwartz marc_schwartz at me.com
Fri Aug 21 04:54:06 CEST 2009


On Aug 20, 2009, at 9:30 PM, Steven Kang wrote:

> Hi all R users,
>
>
> I am trying to extract elements from an array (x as shown below)  
> where the
> difference between the consecutive elements does not equal 1.
>
> The desired output is:
>                j = 6,17,27,38,58,69,79,90
>
> However, the code below only returns:
>                j = 1,69,79,90
>
> I am assuming that "cbind" function is not extracting all the elements
> meeting the condition. In Matlab, j = [] (empty array) would append  
> all the
> elements into this variable j if the conditions are met. I have also  
> tried
> concatenating the elements (j <- c(1, x[i], x[i+1], x[length(x)]),  
> however
> no luck..
>
>> x
> [1]  6  7  8  9 10 11 12 13 14 15 16 17 27 28 29 30 31 32 33 34 35  
> 36 37 38
> 58 59 60 61 62 63 64 65 66 67 68 69 79 80 81 82 83 84 85 86 87 88 89  
> 90
>
>
> i <- 1
> j <- numeric()
> while (i < length(x))
>    {
>    if (x[i] + 1 != x[i+1])
>         j <- cbind(1, x[i], x[i+1], x[length(x)])
> #       j <- c(1, x[i], x[i+1], x[length(x)])
>         i <- i+1
>    }
>
> Please advise any solutions that may enlighten my problem.
>
> Highly appreciate for your help in this matter in advance.
>
> Steve


How about this:

Ind <- which(diff(x) != 1)

j <- x[c(1, sort(c(Ind, Ind + 1)), length(x))]

 > j
[1]  6 17 27 38 58 69 79 90


See ?diff and ?which for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list