[R] filling values in a vector using smaller vector

Milton Huang mph at emotrics.com
Wed Dec 24 10:05:12 CET 2008


Dear list members:

I am looking for an elegant (or efficient) way to accomplish the following:

take a large boolean vector and fill the TRUE values with the values from a 
smaller boolean vector that has a length that is the number of TRUE values of 
the large vector.

Example:

large<- c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE,  TRUE, FALSE, FALSE, FALSE,  
TRUE, FALSE)

small<- c(TRUE, FALSE, TRUE)

desired output = c(FALSE, FALSE, FALSE, *TRUE*, FALSE, FALSE,  *FALSE*, FALSE, 
FALSE, FALSE, *TRUE*, FALSE)

(without the asterisks! )

my first thought as someone new to R was 
ifelse(large,small, large)

but that returns: c(FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE 
FALSE FALSE FALSE) because small is cycled to match the size of large instead 
of the size of the TRUE subset of large.

I am guessing that there is probably a way to do this without writing a loop, 
but I just don't know the syntax.

-mph



More information about the R-help mailing list