有效地将命名列表转换为data.frame [英] Convert named list to a data.frame efficiently
本文介绍了有效地将命名列表转换为data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种有效的方法来进行以下转换:
I'm looking for a efficient way for the following transformation:
示例输入:
ob <- list(a = 2, b = 3)
预期输出:
key value
1 a 2
2 b 3
当前(详细)解决方案:
Current (verbose) solution:
data.frame(key = names(ob), value = unlist(ob, use.names = FALSE))
推荐答案
尝试stack
stack(ob)
# values ind
#1 2 a
#2 3 b
您将需要更改名称.使用setNames
You would need to change the names though. Use setNames
setNames(stack(ob), nm = c("value", "key"))
基准
在处理@Roland的评论时, 请不要使用stack
似乎确实更有效.stack
,而是出于效率原因使用OP的解决方案.
Addressing @Roland's comment, please don't use stack
seems to be more efficient indeed.stack
but OP's solution for efficiency reasons.
n <- 1e5
lst <- as.list(seq_len(n))
names(lst) <- paste0("a", seq_len(n))
library(microbenchmark)
benchmark <- microbenchmark(
snoram = snoram(lst),
markus = markus(lst), times = 50
)
benchmark
#Unit: milliseconds
# expr min lq mean median uq max neval
# snoram 2.475258 2.594479 2.739639 2.652843 2.715575 5.92216 50
# markus 114.387692 119.028200 134.745626 137.524606 144.045112 162.11510 50
到目前为止使用的功能
snoram <- function(l) {
data.frame(key = names(l), value = unlist(l, use.names = FALSE),
stringsAsFactors = FALSE) # this gives a hugh performance gain
# thanks to @Roland
}
markus <- function(l) {
setNames(stack(l), nm = c("value", "key"))
}
这篇关于有效地将命名列表转换为data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文