stakowerflol
stakowerflol

Reputation: 1079

Fill vector with a value to make the length appropriate?

I am wondering is there any primitive function in R to do the same as 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)
} 

so when I run foo(1:9, 1:5) then I should get list of 2 vectors:
1st:
1, 2, 3, 4, 5, 6, 7, 8, 9
2nd:
1, 2, 3, 4, 5, 0, 0, 0, 0

Upvotes: 0

Views: 54

Answers (2)

James
James

Reputation: 66844

I don't think there is but you can simplify your function quite a bit:

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

This can be extended quite easily to take an arbitrary number of inputs:

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

Upvotes: 2

MKR
MKR

Reputation: 20095

The nearest option I can think of is to use qpcR:::cbind.na function. The answer in case of OP's vectors:

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

Upvotes: 0

Related Questions