如何在不重复较短向量的元素的情况下cbind或rbind不同长度的向量?

如何在不重复较短向量的元素的情况下cbind或rbind不同长度的向量?

cbind(1:2, 1:10)  

     [,1] [,2]  

  [1,]    1    1  

  [2,]    2    2  

  [3,]    1    3  

  [4,]    2    4  

  [5,]    1    5  

  [6,]    2    6  

  [7,]    1    7  

  [8,]    2    8  

  [9,]    1    9  

 [10,]    2   10  

我想要一个像下面这样的输出


[,1] [,2]  

[1,] 1 1  

[2,] 2 2  

[3,]   3  

[4,]   4  

[5,]   5  

[6,]   6  

[7,]   7  

[8,]   8  

[9,]   9  

[10,]  10  


慕婉清6462132
浏览 979回答 3
3回答

Smart猫小萌

辅助功能......bind.pad <- function(l, side="r", len=max(sapply(l,length))){&nbsp; if (side %in% c("b", "r")) {&nbsp; &nbsp; out <- sapply(l, 'length<-', value=len)&nbsp; } else {&nbsp; &nbsp; out <- sapply(sapply(sapply(l, rev), 'length<-', value=len, simplify=F), rev)}&nbsp; if (side %in% c("r", "l")) out <- t(out)&nbsp; out}例子:> l <- lapply(c(3,2,1,2,3),seq)> lapply(c("t","l","b","r"), bind.pad, l=l, len=4)[[1]]&nbsp; &nbsp; &nbsp;[,1] [,2] [,3] [,4] [,5][1,]&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA[2,]&nbsp; &nbsp; 1&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp; 1[3,]&nbsp; &nbsp; 2&nbsp; &nbsp; 1&nbsp; &nbsp;NA&nbsp; &nbsp; 1&nbsp; &nbsp; 2[4,]&nbsp; &nbsp; 3&nbsp; &nbsp; 2&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp; 3[[2]]&nbsp; &nbsp; &nbsp;[,1] [,2] [,3] [,4][1,]&nbsp; &nbsp;NA&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp; 3[2,]&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp; 1&nbsp; &nbsp; 2[3,]&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp; 1[4,]&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp; 1&nbsp; &nbsp; 2[5,]&nbsp; &nbsp;NA&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp; 3[[3]]&nbsp; &nbsp; &nbsp;[,1] [,2] [,3] [,4] [,5][1,]&nbsp; &nbsp; 1&nbsp; &nbsp; 1&nbsp; &nbsp; 1&nbsp; &nbsp; 1&nbsp; &nbsp; 1[2,]&nbsp; &nbsp; 2&nbsp; &nbsp; 2&nbsp; &nbsp;NA&nbsp; &nbsp; 2&nbsp; &nbsp; 2[3,]&nbsp; &nbsp; 3&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp; 3[4,]&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA[[4]]&nbsp; &nbsp; &nbsp;[,1] [,2] [,3] [,4][1,]&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp; 3&nbsp; &nbsp;NA[2,]&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp;NA&nbsp; &nbsp;NA[3,]&nbsp; &nbsp; 1&nbsp; &nbsp;NA&nbsp; &nbsp;NA&nbsp; &nbsp;NA[4,]&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp;NA&nbsp; &nbsp;NA[5,]&nbsp; &nbsp; 1&nbsp; &nbsp; 2&nbsp; &nbsp; 3&nbsp; &nbsp;NA
打开App,查看更多内容
随时随地看视频慕课网APP