Combe两个长度不等的向量

时间:2016-01-29 22:08:43

标签: r vector

我想要两个长度不等的向量组合,但rbind()返回像

a <- 1:5
b <- 1:10
rbind(a,b)

#   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# a    1    2    3    4    5    1    2    3    4     5
# b    1    2    3    4    5    6    7    8    9    10

但我希望我的数据是

rbind(a,b)

#   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# a    1    2    3    4    5    0    0    0    0     0
# b    1    2    3    4    5    6    7    8    9    10

并制作带有一层的分层直方图

1 个答案:

答案 0 :(得分:0)

您可以将矢量长度调整为最大长度,这将为您提供NA,并将这些NA替换为0:

lst <- list(a, b)
res <- do.call(rbind, lapply(lst, "length<-", max(lengths(lst))))
res[is.na(res)] <- 0
res
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    1    2    3    4    5    0    0    0    0     0
# [2,]    1    2    3    4    5    6    7    8    9    10