追加R中的对象名单在固定的时间里,O(1)? [英] Append an object to a list in R in amortized constant time, O(1)?

查看:213
本文介绍了追加R中的对象名单在固定的时间里,O(1)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一些ř列表 MYLIST ,您可以将一个项目 OBJ 来它像这样:

If I have some R list mylist, you can append an item obj to it like so:

mylist[[length(mylist)+1]] <- obj

但肯定有一些更紧凑的方式。当我在r是新的,我试着写 lappend()像这样:

lappend <- function(lst, obj) {
    lst[[length(lst)+1]] <- obj
    return(lst)
}

但当然,这并不因于R的呼叫按姓名语义( LST 有效地根据呼叫复制,所以改变工作LST 不在范围之内可见 lappend()。我知道你可以做到环境在R功能黑客到的范围之内到达你功能与变异调用环境,但似乎像一个大铁锤写一个简单的附加功能。

but of course that doesn't work due to R's call-by-name semantics (lst is effectively copied upon call, so changes to lst are not visible outside the scope of lappend(). I know you can do environment hacking in an R function to reach outside the scope of your function and mutate the calling environment, but that seems like a large hammer to write a simple append function.

任何人都可以提出这样做​​的更华丽的方式?奖励积分,如果它适用于载体和列表。

Can anyone suggest a more beautiful way of doing this? Bonus points if it works for both vectors and lists.

推荐答案

如果它是字符串列表,只需要使用 C()功能:

If it's a list of string, just use the c() function :

R> LL <- list(a="tom", b="dick")
R> c(LL, c="harry")
$a
[1] "tom"

$b
[1] "dick"

$c
[1] "harry"

R> class(LL)
[1] "list"
R> 

这也对向量的作品,所以我会得到加分?

That works on vectors too, so do I get the bonus points?

编辑(2015年 - 2月-01):的这篇文章快到了其第五个生日。一些读者一直在重复什么缺点呢,所以通过各种手段也看到一些下面的意见。为列表类型的一个建议:

Edit (2015-Feb-01): This post is coming up on its fifth birthday. Some kind readers keep repeating any shortcomings with it, so by all means also see some of the comments below. One suggestion for list types:

newlist <- list(oldlist, list(someobj))

在一般情况下,R型可以使它很难对所有类型和用途之一,只是一个成语。

In general, R types can make it hard to have one and just one idiom for all types and uses.

这篇关于追加R中的对象名单在固定的时间里,O(1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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