斗士狗 2010-03-13 00:14 采纳率: 0%
浏览 456
已采纳

将一个对象附加到 r 中的一个列表中,按照分期付款的常量时间,o (1) ?

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

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

But surely there is some more compact way. When I was new at R, I tried writing lappend() like so:

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

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.

转载于:https://stackoverflow.com/questions/2436688/append-an-object-to-a-list-in-r-in-amortized-constant-time-o1

  • 写回答

16条回答 默认 最新

  • csdnceshi62 2010-03-13 01:56
    关注

    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?

    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))
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据