Skip to content

Instantly share code, notes, and snippets.

@emitanaka
Last active April 18, 2021 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emitanaka/4561dc25d500cdf522fce19248a66173 to your computer and use it in GitHub Desktop.
Save emitanaka/4561dc25d500cdf522fce19248a66173 to your computer and use it in GitHub Desktop.
Combine elements like `c` but preserving the attributes
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