user7649990
user7649990

Reputation:

Equalizing the length of 3 vectors in R based on a rule

Suppose I have the 3 vectors x, y, and z which are of unequal length (see code below).

I was wondering how I could have the last member of the shorter vectors (here x and y) be repeated such that the 3 vectors always become of equal length whenever they are of unequal length?

For example, in the example below 2 in x be repeated 2 times, and "hi" in y be repeated 3 times.

x = c(1, 2) ; y = c("hi") ; z = c(1, 2, 3, 4)

Upvotes: 1

Views: 166

Answers (1)

d.b
d.b

Reputation: 32548

foo = function(...){
    ml = list(...)
    L = max(lengths(ml))
    lapply(ml, function(x) c(x, rep(tail(x, 1), L - length(x))))
}
foo(x, y, z)
#[[1]]
#[1] 1 2 2 2

#[[2]]
#[1] "hi" "hi" "hi" "hi"

#[[3]]
#[1] 1 2 3 4

Upvotes: 3

Related Questions