[英]Combining a list of named vectors without mangling the names
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. 我需要拆分一个整数矢量(名称中包含字符),以便与parallel::parSapply()
结合使用,然后将它们重新组合在一起。 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
将数据转换回命名向量时,名称会混乱:
> 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 ): 我正在寻找以下结果(除了它应该与任何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
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. 在不改变的“文本”结构的一种选择是改变名称vector
( unlist(text)
用) names
onjects的内部list
元素。
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
或者,如果可以删除“文本”对象的名称,请将“文本”的名称设置为NULL,然后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
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))
或者,正如@RichardScriven在注释中指出的那样,您可以按以下步骤进行操作而无需在源变量中删除名称: do.call("c", c(text, use.names = FALSE))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.