如何在不重复较短向量的元素的情况下 cbind 或 rbind 不同长度的向量? [英] How to cbind or rbind different lengths vectors without repeating the elements of the shorter vectors?
本文介绍了如何在不重复较短向量的元素的情况下 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
我想要一个像下面这样的输出
I want an output like below
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
推荐答案
诀窍是让所有输入的长度相同.
The trick is to make all your inputs the same length.
x <- 1:2
y <- 1:10
n <- max(length(x), length(y))
length(x) <- n
length(y) <- n
如果您希望输出为数组,则 cbind
有效,但您会获得额外的 NA
值来填充矩形.
If you want you output to be an array, then cbind
works, but you get additional NA
values to pad out the rectangle.
cbind(x, y)
x y
[1,] 1 1
[2,] 2 2
[3,] NA 3
[4,] NA 4
[5,] NA 5
[6,] NA 6
[7,] NA 7
[8,] NA 8
[9,] NA 9
[10,] NA 10
要去掉 NA
,输出必须是一个列表.
To get rid of the NA
s, the output must be a list.
Map(function(...)
{
ans <- c(...)
ans[!is.na(ans)]
}, 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
.
这篇关于如何在不重复较短向量的元素的情况下 cbind 或 rbind 不同长度的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文