Manuel Ramon
2009-Nov-25 21:46 UTC
[R] Insert elements into a vector in a defined positions
Dear R users, I have a vector of length n and I want to insert some elements (in my case the NA string) into a defined positions. For example, my vector is z1 and I want to add NA's in positions 4, 6 y 7 so after that, my new vector, z2, should have a length of 10+3. z1 <- 1:10 id <- c(4,6,7) # And z2 should be: z2 <- c(1,2,3,NA,4,5,NA,NA,6,7,8,9,10) Anyone knows how can I do that? Thank you. ----- Manuel Ram?n Fern?ndez Group of Reproductive Biology (GBR) University of Castilla-La Mancha (Spain) mramon at jccm.es -- View this message in context: http://old.nabble.com/Insert-elements-into-a-vector-in-a-defined-positions-tp26520841p26520841.html Sent from the R help mailing list archive at Nabble.com.
Rolf Turner
2009-Nov-25 22:48 UTC
[R] Insert elements into a vector in a defined positions
On 26/11/2009, at 10:46 AM, Manuel Ramon wrote:> > Dear R users, > I have a vector of length n and I want to insert some elements (in > my case > the NA string) into a defined positions. For example, my vector is > z1 and I > want to add NA's in positions 4, 6 y 7 so after that, my new > vector, z2, > should have a length of 10+3. > > z1 <- 1:10 > id <- c(4,6,7) > > # And z2 should be: > z2 <- c(1,2,3,NA,4,5,NA,NA,6,7,8,9,10) > > Anyone knows how can I do that?At first I thought append() might work ... but the "after" argument to append seems to have to be of length 1. How about: z2 <- numeric(length(z1)+length(id)) z2[id] <- NA z2[!is.na(z2)] <- z1 A bit kludgy, but it appears to work. cheers, Rolf Turner ###################################################################### Attention:\ This e-mail message is privileged and confid...{{dropped:9}}