[R] how to extract consecutive subvetors of different lengths from an existing vector and create a matrix

arun smartpink111 at yahoo.com
Tue Feb 25 16:34:03 CET 2014


One way would be:

res <- t(sapply(split(y,rep(seq_along(n),n)),function(x) {if(length(x) < max(n)) c(x,rep(NA,max(n)-length(x))) else x}))

Dear all, 

my question regards how to subset an existing vector in 
subvectors of different lengths and then create a matrix. See example 

I have vectors: 


and I'd like to create the matrix A of the following form: 

1 1  1 
0 0 NA 
1 1 NA 

I'd like to "cut" y sequentially based on information in vector 
n, that is, generating 3 subvectors (the first with the first 3 elements
 of y, the second with the other 2 elements of y, and the last one with 
the latter 2 elements of y) and creating a matrix A (with dimensions, 
no.of rows=length(n), no. of col=max(n) and including NAs where 

Hope to have been clear. 


More information about the R-help mailing list