R and rbind making entries without the same length be zero

吃可爱长大的小学妹 提交于 2019-12-03 08:38:13
Ricardo Saporta

use the 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 it works: Indexing a vector by a value larger than its length returns a value of NA at that index point.

 #eg: 
{1:3}[c(3,5,1)]
#[1]  3 NA  1

Thus, if you index the shorter one by the indecies of the longer one, you willl get all of the values of the shorter one plus a series of NA's


A generalization:

v <- list(v1, v2)
n <- max(sapply(v, length))
do.call(rbind, lapply(v, `[`, seq_len(n)))
Nishanth

In case you have many vectors to rbind finding longer and shorter vectors could be tedious. In which case this is an option:

require(plyr)

rbind.fill.matrix(t(v1), t(v2))

or,

rbind.fill(as.data.frame(t(v1)), as.data.frame(t(v2)))

Although I think Ricardo has offered a nice solution, something like this would also work applying a function to a list of the vectors you wish to bind. You could specify the character to fill with as well.

test <- list(v1,v2)
maxlen <- max(sapply(test,length))
fillchar <- 0
do.call(rbind,lapply(test, function(x) c(x, rep(fillchar, maxlen - length(x) ) )))

Or avoiding all the do.call(rbind madness:

t(sapply(test, function(x) c(x, rep(fillchar, maxlen - length(x)))))

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#[1,]    1    2    3    4    8    5    3   11
#[2,]    9    5    2    0    0    0    0    0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!