Reputation: 1725
How do I combine a list of named vectors? I need to split a vector of integers (with characters for names) for use with parallel::parSapply()
and combine them back again. Example code:
text <- 1:26
names(text) <- letters
n <- 4
text <- split(text, cut(1:length(text),breaks=n,labels=1:n))
# text <- parSapply(..., text, ...) would go here in the actual code
However, the names get mangled when I use unlist
to convert the data back into a named vector:
> unlist(text)
1.a 1.b 1.c 1.d 1.e 1.f 1.g 2.h 2.i 2.j 2.k 2.l 2.m 3.n 3.o 3.p 3.q 3.r 3.s 4.t 4.u 4.v
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
4.w 4.x 4.y 4.z
23 24 25 26
What I'm looking for is the following result (except that it should work with any value of n):
> c(text[[1]],text[[2]],text[[3]],text[[4]])
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Upvotes: 3
Views: 687
Reputation: 4686
You can remove the list elements names first then there won't be compound naming happening.
> names(text) <- NULL
> do.call(c, text)
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Same as
> unlist(text)
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Or as @RichardScriven pointed out in the comment, you can do it as follows without removing the name in the source variable: do.call("c", c(text, use.names = FALSE))
Upvotes: 2
Reputation: 887501
One option without changing the structure of 'text' would be to change the names of the vector
(unlist(text)
) with the names
of onjects within the list
elements.
setNames(unlist(text), unlist(sapply(text, names)))
# a b c d e f g h i j k l m n o p q r s t u v w x y z
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Or if it is okay to remove the names of the 'text' object, set the names of 'text' to NULL and then unlist
unlist(setNames(text, NULL))
# a b c d e f g h i j k l m n o p q r s t u v w x y z
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Upvotes: 4