[R] Generate a list of all subsequence of length k from an array

David Winsemius dwinsemius at comcast.net
Tue Jun 22 16:49:28 CEST 2010


On Jun 22, 2010, at 2:35 AM, Ron Shefi wrote:

>
> Hi,
> I would like to generate a list of all subsequence of length k from  
> an  array with length n (k < n). The result should be organized in a  
> matrix.
> So the matrix should look like the following whereas each row is one  
> of a subsequence of len k.
>
> [a[1:k],
> a[2:(k+1)]
> a[3:(k+2)]
> ...
> a[(:n]
>
> Is there away to do this with sapply method?

I suppose you could try (untested in absence of example):

sapply(1:(n-k+1), function(x) { a[x:(x+k)] })

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list