Hi,
You could also do:

mat1 <- matrix(NA,ncol=max(n),nrow=length(n))
 mat1[cbind(rep(seq_along(n),n),seq_len(sum(n))- 
rep(cumsum(c(0L,n[-length(n)])),n))] <- y
mat1
A.K.




On Tuesday, February 25, 2014 10:34 AM, arun <[email protected]> wrote:
Hi,

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}))
A.K.


Dear all, 

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

I have vectors: 

y<-c(1,1,1,0,0,1,1) 
n<-c(3,2,2) 

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 
necessary. 

Hope to have been clear. 

Bex

______________________________________________
[email protected] 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.

Reply via email to