简体   繁体   English

如何将两个向量的元素合并到列表中并根据原始向量保留名称?

[英]How to join two vectors' elements in a list and keep names according to origin vector?

I'm trying to find an elegant way to link function parameters and an httr 's call query list. 我正在尝试找到一种优雅的方法来链接函数参数和httr的调用查询列表。 Assume we have two character vectors, indicating animals and colors 假设我们有两个字符向量,分别表示动物和颜色

animals = "dog"
colors = "red"

If I use the query parameter 如果我使用查询参数

list(animal=animals,color=colors)

it will produce the expected result. 它将产生预期的结果。 On the other hand, if I want multiple parameters for one of the components 另一方面,如果我要为组件之一提供多个参数

animals = c("dog","cat")

the same list would create 相同的列表将创建

$animal
[1] "dog" "cat"

$color
[1] "red"

when httr requires a list like httr需要类似

$animal
[1] "dog"

$animal
[1] "cat"

$color
[1] "red"

How can I elegantly create the appropriate list, where instead of having a character vector as an element, multiple elements with the same name would be created? 如何优雅地创建适当的列表,而不是使用字符向量作为元素,而是创建多个具有相同名称的元素?

Try: 尝试:

foo <- list(animals = c("dog","cat"), color = "red")
foo <- as.list(unlist(foo))
foo <- setNames(foo, gsub("[[:digit:]]", "", names(foo)))

The list becomes less useful since selecting by name doesn't work, but should be the format you want. 由于按名称选择不起作用,但该列表应为您想要的格式,因此该列表的用处不大。 Renaming isn't great if your list has numbers, but that might be something you have to work out separately. 如果您的列表中有数字,重命名不是很好,但这可能是您必须单独解决的问题。

Update: 更新:

I don't like renaming with regular expressions. 我不喜欢使用正则表达式重命名。 You can also try something like this to remove that last line: 您也可以尝试执行以下操作删除最后一行:

as.list(setNames(unlist(foo), rep(names(foo), sapply(foo, length))))

It's a little more exact that using setNames and gsub . 使用setNamesgsub更加精确。

c(animals=as.list(animals),colors=colors)
$animals1
[1] "dog"

$animals2
[1] "cat"

$colors
[1] "red"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM