camr_interleave
The following function is proposed for inclusion. Given two or more vectors, the function overrides missing values in the first with values in the second, the third, the fourth, and so on.
interleave2 <- function (v1, v2, .lgl_ignore_overlapping=FALSE, .chr_err_common=NULL) {
assert_string(.chr_err_common, null.ok=TRUE)
vlgl_v1na <- is.na(v1)
vlgl_common <- !vlgl_v1na & !is.na(v2)
if (any(vlgl_common) & !.lgl_ignore_overlapping) {
chr_problem <- paste(which(vlgl_common), collapse=' ')
if (is.null(.chr_err_common))
stop('Vectors ', substitute(v1), ' and ', substitute(v2),
' are both non-missing at indicies: ', chr_problem, '.'
)
stop(.chr_err_common, chr_problem, '.')
}
v1[vlgl_v1na] <- v2[vlgl_v1na]
v1
}
interleave <- function (..., .lgl_ignore_overlapping=FALSE) {
int_len <- ...length()
if (int_len < 2)
stop('Must provide at least two vector arguments.')
v_acc <- ..1
for (idx in seq_len(...length() - 1) + 1) {
v_acc <- interleave2(
v_acc,
...elt(idx),
.lgl_ignore_overlapping=.lgl_ignore_overlapping,
.chr_err_common=paste('Vector at argument', idx, 'is non-missing in the same indicies as a previous argument: ')
)
}
v_acc
}
The following table describes the expected behavior (test with .lgl_ignore_overlapping=T
).
A | B | C | interleave(A,B) | interleave(A,B,C) |
---|---|---|---|---|
'l' | 14 | 1 | 'l' | 'l' |
'm' | 15 | 2 | 'm' | 'm' |
'n' | NA | 3 | 'n' | 'n' |
NA | 17 | 4 | 17 | 17 |
'p' | 18 | 5 | 'p' | 'p' |
NA | NA | 6 | NA | 6 |
'r' | 20 | 7 | 'r' | 'r' |
NA | NA | NA | NA | NA |
@kp390 @be931 @lvn3 Please react with a thumbs up to accept the proposal or leave a comment with modifications.
Edited by Pascale, Michael Philip