vector - R and rbind making entries without the same length be zero -
say have 2 vectors v1 , v2 , want call rbind(v1, v2). however, supposed length(v1) > length(v2). documentation have read shorter vector recycled. here example of "recycling":
> v1 <- c(1, 2, 3, 4, 8, 5, 3, 11) > v2 <- c(9, 5, 2) > rbind(v1, v2) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] v1 1 2 3 4 8 5 3 11 v2 9 5 2 9 5 2 9 5 - is there straightforward way can stop
v2being recycled , instead make remaining entries 0? - is there better way build vectors , matrices?
all appreciated!
use following:
rbind(v1, v2=v2[seq(v1)]) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] v1 1 2 3 4 8 5 3 11 v2 9 5 2 na na na na na why works: indexing vector value larger length returns value of na @ index point.
#eg: {1:3}[c(3,5,1)] #[1] 3 na 1 thus, if index shorter 1 indecies of longer one, willl of values of shorter 1 plus series of na's
a generalization:
v <- list(v1, v2) n <- max(sapply(v, length)) do.call(rbind, lapply(v, `[`, seq_len(n)))
Comments
Post a Comment