r - combine two named vectors with missing values in matrix -


i have named vector x:

  x <- seq(10, 80, 10) names(x) <- month.abb[1:8] 

...and named vector y:

  y <- seq(10, 110, 10) names(y) <- month.abb[2:12] 

i need combine x , y in matrix. missing months in either x or y, values should 0 (not na). matrix need:

xy <- matrix(c(c(seq(10, 80, 10), 0, 0, 0, 0), c(0, seq(10, 110, 10))), nrow = 2, ncol = 12, byrow = true,              dimnames = list(c("x", "y"),                              month.abb))  

i'm having trouble programatically combining x , y matrix. advice please?

try rbind.fill.matrix "plyr" package:

library(plyr) temp <- rbind.fill.matrix(t(x), t(y)) temp[is.na(temp)] <- 0 temp #      jan feb mar apr may jun jul aug sep oct nov dec # [1,]  10  20  30  40  50  60  70  80   0   0   0   0 # [2,]   0  10  20  30  40  50  60  70  80  90 100 110 

sticking base r, possible use following:

a <- matrix(0, ncol = 12) colnames(a) <- month.abb temp <- list(x, y) do.call(rbind,          lapply(seq_along(list(x, y)), function(z) {           a[, names(temp[[z]])] <- temp[[z]]                   })) #      jan feb mar apr may jun jul aug sep oct nov dec # [1,]  10  20  30  40  50  60  70  80   0   0   0   0 # [2,]   0  10  20  30  40  50  60  70  80  90 100 110 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -