Combine elements like `c` but preserving the attributes
This file contains 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