select array data in which column n's values rise consecutively

#1
I want to select only the data from an array that is sequential by column n. For example:

Code:
n <- c(1, 2, 4, 6, 7, 8, 9, 11)
x <- c(10, 20, 30, 40, 50, 60, 80, 90)
y <- c(60, 20, 40, 90, 10, 30, 50, 40)

a <- cbind(n,x,y)

a
      n  x  y
[1,]  1 10 60
[2,]  2 20 20
[3,]  4 30 40
[4,]  6 40 90
[5,]  7 50 10
[6,]  8 60 30
[7,]  9 80 50
[8,] 11 90 40
I want to create array b with rows 1,2, 4-7, because the n increases by an integer consecutively (n= 1,2, 6-9). Thus, my output of array b should look like:

Code:
  n  x  y
[1,]  1 10 60
[2,]  2 20 20
[3,]  6 40 90
[4,]  7 50 10
[5,]  8 60 30
[8,]  9 80 50
I tried to use the code here (http://r.789695.n4.nabble.com/Efficient-way-to-find-consecutive-integers-in-vector-td843506.html) to solve this problem, but it works for vectors, not arrays. Besides, this seems like an easier problem that I am over-complicating. Before this point, I sorted a by increasing integers in n, so I only need to remove data that is not sequential. I'd appreciate any help, thanks.
 

Dason

Ambassador to the humans
#2
So just use the solution on the vector that is the column of the matrix you're interested in and then use those indices to index the matrix.
 

trinker

ggplot2orBust
#3
I'm in a hurry so I can't explain the logic but this works:

Code:
x <- c(FALSE, diff(a[, 1]) == 1)
y <- rle(x)
x[head((cumsum(y[[1]])), -1)[!y[[2]]]] <- TRUE
a[x, ]

[COLOR="gray"]##      n  x  y
## [1,] 1 10 60
## [2,] 2 20 20
## [3,] 6 40 90
## [4,] 7 50 10
## [5,] 8 60 30
## [6,] 9 80 50[/COLOR]