我想知道R中是否存在与foo
相同的原始函数:
foo <- function(a, b) {
makeSmallerVectAsLonger <- function(smaller, longer) {
lengthDiff <- length(longer) - length(smaller)
c(smaller, rep(0, lengthDiff))
}
lengthA <- length(a)
lengthB <- length(b)
if(lengthA > lengthB) {
b <- makeSmallerVectAsLonger(b, a)
}
if(lengthA < lengthB) {
a <- makeSmallerVectAsLonger(a, b)
}
list(a, b)
}
所以当我运行foo(1:9, 1:5)
时,我应该得到2个向量的列表:
1:
1, 2, 3, 4, 5, 6, 7, 8, 9
第二:
1, 2, 3, 4, 5, 0, 0, 0, 0
答案 0 :(得分:2)
我认为没有,但你可以简化你的功能:
expand_vecs <- function(a,b)
{
base <- numeric(max(length(a),length(b)))
lapply(list(a,b), function(x) replace(base,seq_along(x),x))
}
expand_vecs(1:9, 1:5)
[[1]]
[1] 1 2 3 4 5 6 7 8 9
[[2]]
[1] 1 2 3 4 5 0 0 0 0
这可以很容易地扩展到任意数量的输入:
expand_vecs <- function(..., default=0)
{
vecs <- list(...)
base_length <- max(sapply(vecs,length))
base <- rep(default,base_length)
lapply(vecs, function(x) replace(base,seq_along(x),x))
}
expand_vecs(rnorm(5),sample(1:10,3),3)
[[1]]
[1] -1.7961210 -0.2844418 -1.1059407 -0.6908350 -0.7752376
[[2]]
[1] 9 10 8 0 0
[[3]]
[1] 3 0 0 0 0
答案 1 :(得分:0)
我能想到的最近的选项是使用qpcR:::cbind.na
函数。 OP的向量答案:
qpcR:::cbind.na(1:9, 1:5)
# [,1] [,2]
# [1,] 1 1
# [2,] 2 2
# [3,] 3 3
# [4,] 4 4
# [5,] 5 5
# [6,] 6 NA
# [7,] 7 NA
# [8,] 8 NA
# [9,] 9 NA