挑战:优化不公开[简单] [英] challenge: optimize unlisting [easy]

查看:68
本文介绍了挑战:优化不公开[简单]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为最近SO有点慢,所以我提出了一个简单的问题.如果大型鱼类能留在替补席上,并给菜鸟一个回应的机会,我将不胜感激.

Because SO is a bit slow lately, I'm posting an easy question. I would appreciate it if big fishes stayed on the bench for this one and give rookies a chance to respond.

有时,我们的对象中包含大量可笑的大型列表元素(向量).您如何将这个对象取消列出"到单个向量中.证明您的方法比unlist()快.

Sometimes we have objects that have a ridiculous amount of large list elements (vectors). How would you "unlist" this object into a single vector. Show proof that your method is faster than unlist().

推荐答案

如果您不需要名称,并且列表深一层,那么您可以击败

If you don't need names and your list is one level deep, then if you can beat

.Internal(unlist(your_list, FALSE, FALSE))

接下来的一年,我将投票支持您在SO方面所做的一切!!

I will vote up everything you do on SO for the next 1 year!!!

[更新:如果需要非唯一名称,并且列表不是递归的,则此版本可将未列出的名称提高100倍

[Update: if non-unique names are needed and the list is not recursive, here is a version which improves over the unlist 100 times

 myunlist <- function(l){
    names <- names(l)
    vec <- unlist(l, F, F)
    reps <- unlist(lapply(l, length), F, F)
    names(vec) <- rep(names, reps)
    vec
    }

 myunlist(list(a=1:3, b=2))
 a a a b 
 1 2 3 2 

 > tl <- list(a = 1:20000, b = 1:5000, c = 2:30)
 > system.time(for(i in 1:200) unlist(tl))
 user  system elapsed 
 22.97    0.00   23.00 

 > system.time(for(i in 1:200) myunlist(tl))
 user  system elapsed 
 0.2     0.0     0.2 

 > system.time(for(i in 1:200) unlist(tl, F, F))
 user  system elapsed 
 0.02    0.00    0.02 

]

[Update2:响应来自Richie Cotton的Nr3.

[Update2: Responce to challenge Nr3 from Richie Cotton.

bigList3 <- replicate(500, rnorm(1e3), simplify = F)

unlist_vit <- function(l){
    names(l) <- NULL
    do.call(c, l)
    }

library(rbenchmark)

benchmark(unlist = unlist(bigList3, FALSE, FALSE),
          rjc    = unlist_rjc(bigList3),
          vit    = unlist_vit(bigList3),
          order  = "elapsed",
          replications = 100,
          columns = c("test", "relative", "elapsed")
          )

    test  relative elapsed
1 unlist   1.0000    2.06
3    vit   1.4369    2.96
2    rjc   3.5146    7.24

]

PS:我认为大鱼"是声望比您高的一条.所以我在这里很小:).

PS: I assume a "big fish" is the one with more reputation than you. So I am pretty much small here :).

这篇关于挑战:优化不公开[简单]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆