Better way to convert list to vector?

若如初见. 提交于 2019-11-26 06:43:24

问题


I have a list of named values:

myList <- list(\'A\'=1, \'B\'=2, \'C\'=3)

I want a vector with the value 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?


回答1:


Use unlist with use.names = FALSE argument.

unlist(myList, use.names=FALSE)



回答2:


purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)

purrr::flatten_dbl(myList)
## [1] 1 2 3



回答3:


This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))


来源:https://stackoverflow.com/questions/17094774/better-way-to-convert-list-to-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!