Reputation: 13
FIRST SITUATION:
I have the vectors v1 and v2 v1 <- c(1, 2, 4, 5, 7, 8, 10, 11, 13, 15) v2 <- c(3, 4, 5, 23, NA, 14, NA)
I want to create a function (I don't want want use r functions for these 3 cases) to sum each values and because the length is different, I want to put a 0 in this missing places.
SECOND SITUATION
I want to sum each values, just like the first situation, but the sum action must stop when reaches the last value of the smaller vector.
THIRD SITUATION
I want to combine each values and repeat them when the there is a smaller one.
As a result, it would be: 4, 6, 9, 28, NA, 22, NA, 14, 17, 20
Upvotes: 0
Views: 139
Reputation: 886948
We can get the length same
mx <- max(length(v1), length(v2))
c(v2, rep(0, mx - length(v2))) + c(v1, rep(0, mx - length(v1)))
#[1] 4 6 9 28 NA 22 NA 11 13 15
For second situation, use min
mn <- min(length(v1), length(v2))
v2[seq_len(mn)] + v1[seq_len(mn)]
#[1] 4 6 9 28 NA 22 NA
Or for third situation
c(v2, v2[seq_len(mx - length(v2))]) + c(v1, v1[seq_len(mx - length(v1))])
#[1] 4 6 9 28 NA 22 NA 14 17 20
It can be converted to a function
f1 <- function(vec1, vec2, method = "min") {
switch(method,
min = {
mn <- min(length(vec1), length(vec2))
vec1[seq_len(mn)] + vec2[seq_len(mn)]
},
max = {
mx <- max(length(vec1), length(vec2))
c(vec2, rep(0, mx - length(vec2))) + c(vec1, rep(0, mx - length(vec1)))},
recycle = {
mx <- max(length(vec1), length(vec2))
c(vec2, vec2[seq_len(mx - length(vec2))]) + c(vec1, vec1[seq_len(mx - length(vec1))])
})
}
f1(v1, v2)
#[1] 4 6 9 28 NA 22 NA
f1(v1, v2, "max")
#[1] 4 6 9 28 NA 22 NA 11 13 15
f1(v1, v2, "recycle")
#[1] 4 6 9 28 NA 22 NA 14 17 20
Upvotes: 1