Skip to content

Instantly share code, notes, and snippets.

@TimTeaFan
Created April 18, 2021 11:05
Show Gist options
  • Save TimTeaFan/3061b4915bd0b52c4b5177572121c590 to your computer and use it in GitHub Desktop.
Save TimTeaFan/3061b4915bd0b52c4b5177572121c590 to your computer and use it in GitHub Desktop.
combine and keep attributes of same length
l1 <- structure(list(x = 1), attr = 1)
l2 <- structure(list(y = 2), attr = 2)
d <- function(...) {
dots <- match.call(expand.dots = FALSE)$...
attr_ls <- lapply(dots, function(x) attributes(get(as.character(x))))
attr_ls <- lapply(purrr::transpose(attr_ls), unlist)
out <- c(...)
ln_out <- length(out)
if (!all(unlist(lapply(attr_ls, function(x) length(x) == ln_out)))) {
stop("All attributes must have the same length as the output object.")
}
attributes(out) <- attr_ls
out
}
# works
d(l1, l2)
# test: throws error
l3 <- structure(list(y = 2))
d(l1, l3)
# test: throws error
l4 <- structure(list(y = 2), attr = c("a", "b"))
d(l1, l4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment