Last active
April 18, 2021 09:40
-
-
Save emitanaka/4561dc25d500cdf522fce19248a66173 to your computer and use it in GitHub Desktop.
Combine elements like `c` but preserving the attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x <- structure(list(x = 1), "attr" = 2) | |
y <- structure(list(y = 3), "attr" = 1) | |
l <- list(x, y) | |
out <- do.call(c, l) | |
# doesn't quite work (notice the name) | |
out2 <- lapply(seq_along(out), function(i) { | |
attributes(out[[i]]) <- attributes(l[[i]]) | |
out[[i]] | |
}) | |
names(out2) <- names(out) # adding the names back | |
str(out2) | |
#> List of 2 | |
#> $ x: Named num 1 | |
#> ..- attr(*, "names")= chr "x" | |
#> ..- attr(*, "attr")= num 2 | |
#> $ y: Named num 3 | |
#> ..- attr(*, "names")= chr "y" | |
#> ..- attr(*, "attr")= num 1 | |
# patchy solution | |
out <- do.call(c, l) | |
for(i in seq_along(out)) { | |
attributes(out[[i]]) <- attributes(l[[i]]) | |
} | |
str(out) | |
#> List of 2 | |
#> $ x: Named num 1 | |
#> ..- attr(*, "names")= chr "x" | |
#> ..- attr(*, "attr")= num 2 | |
#> $ y: Named num 3 | |
#> ..- attr(*, "names")= chr "y" | |
#> ..- attr(*, "attr")= num 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment