list 将列表转换为向量的更好方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17094774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better way to convert list to vector?
提问by sharoz
I have a list of named values:
我有一个命名值列表:
myList <- list('A'=1, 'B'=2, 'C'=3)
I want a vector with the value 1:3
我想要一个带有值的向量 1:3
I can't figure out how to extract the values without defining a function. Is there a simpler way that I'm unaware of?
我不知道如何在不定义函数的情况下提取值。有没有我不知道的更简单的方法?
library(plyr)
myvector <- laply(myList, function(x) x)
Is there something akin to myList$Values
to strip the names and return it as a vector?
是否有类似于myList$Values
剥离名称并将其作为向量返回的东西?
回答by Arun
Use unlist
with use.names = FALSE
argument.
unlist
与use.names = FALSE
参数一起使用。
unlist(myList, use.names=FALSE)
回答by hrbrmstr
purrr::flatten_*()
is also a good option. the flatten_*
functions add thin sanity checks and ensure type safety.
purrr::flatten_*()
也是不错的选择。这些flatten_*
函数添加了薄的完整性检查并确保类型安全。
myList <- list('A'=1, 'B'=2, 'C'=3)
purrr::flatten_dbl(myList)
## [1] 1 2 3
回答by canevae
This can be done by using unlist
before as.vector
.
The result is the same as using the parameter use.names=FALSE
.
这可以通过使用unlist
before来完成as.vector
。结果与使用参数相同use.names=FALSE
。
as.vector(unlist(myList))