猿问
下载APP

如何在不重复较短向量的元素的情况下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
浏览 54回答 3
3回答

繁星淼淼

诀窍是使所有输入的长度相同。x <- 1:2y <- 1:10n <- max(length(x), length(y))length(x) <- n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;length(y) <- n如果您希望输出为数组,则cbind可以正常工作,但是您可以获得其他NA值来填充矩形。cbind(x, y)&nbsp; &nbsp; &nbsp; &nbsp;x&nbsp; y&nbsp;[1,]&nbsp; 1&nbsp; 1&nbsp;[2,]&nbsp; 2&nbsp; 2&nbsp;[3,] NA&nbsp; 3&nbsp;[4,] NA&nbsp; 4&nbsp;[5,] NA&nbsp; 5&nbsp;[6,] NA&nbsp; 6&nbsp;[7,] NA&nbsp; 7&nbsp;[8,] NA&nbsp; 8&nbsp;[9,] NA&nbsp; 9[10,] NA 10要摆脱NAs,输出必须是一个列表。Map(function(...)&nbsp;&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; ans <- c(...)&nbsp; &nbsp; &nbsp; ans[!is.na(ans)]&nbsp; &nbsp;}, as.list(x), as.list(y))[[1]][1] 1 1[[2]][1] 2 2[[3]][1] 3[[4]][1] 4[[5]][1] 5[[6]][1] 6[[7]][1] 7[[8]][1] 8[[9]][1] 9[[10]][1] 10编辑:我交换mapply(..., SIMPLIFY = FALSE)了Map。

月关宝盒

我遇到了类似的问题,我想建议一些额外的解决方案,我希望,有些可能会有用。解决方案相当简单,并使用qpcR包和提供的cbind.na功能。例x <- 1:2y <- 1:10dta <- qpcR:::cbind.na(x, y)结果> head(dta)&nbsp; &nbsp; &nbsp; x y[1,]&nbsp; 1 1[2,]&nbsp; 2 2[3,] NA 3[4,] NA 4[5,] NA 5[6,] NA 6一边评论按照OP的原始示例,可以轻松删除列名称:colnames(dta) <- NULL该操作将完整地产生所需的输出:> head(dta)&nbsp; &nbsp; &nbsp;[,1] [,2][1,]&nbsp; &nbsp; 1&nbsp; &nbsp; 1[2,]&nbsp; &nbsp; 2&nbsp; &nbsp; 2[3,]&nbsp; &nbsp;NA&nbsp; &nbsp; 3[4,]&nbsp; &nbsp;NA&nbsp; &nbsp; 4[5,]&nbsp; &nbsp;NA&nbsp; &nbsp; 5[6,]&nbsp; &nbsp;NA&nbsp; &nbsp; 6

慕姐829404

辅助功能......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; &n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p; &nbsp;NA
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答