luciano
luciano

Reputation: 13802

combine two named vectors with missing values in matrix

I have a named vector x:

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

...and a named vector y:

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

I need to combine x and y in a matrix. For missing months in either x or y, the values should be 0 (not NA). This is the matrix I 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 and y into a matrix. Any advice please?

Upvotes: 1

Views: 2177

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193637

Try rbind.fill.matrix from the "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 with base R, it is also possible to just use something like the 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]]
          A
        }))
#      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

Upvotes: 1

Related Questions