rep()第一级列表

时间:2012-02-25 23:16:18

标签: r list

我希望使用rep()将列表扩展到给定长度,如:

n = 5
l = 1:3
rep(l, length=n)

但是,我的列表有两种形式,嵌套或非嵌套:

l1 <- list(a=1, b=2)
l2 <- list(list(a=1, b=2), list(x=1, y=2))

rep(l2, length=n) # as desired

rep(l1, length=n) # result is a single list, where I really want 
rep(list(l1), length=n) # instead

要解决此问题,我可能需要将有问题的l1标识为“第一级”,并在应用list()之前将其包装到rep()。这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

这是一个想法:

replist <- function(ls, n){
  ls <- 
  if(sum(sapply(ls, class) != "list") == 0){  # T: all list elements are lists
    ls
  } else {
    list(ls)
  }  
  rep(ls, length = n)
}

identical(replist(l2, 3), rep(l2, length=3))        # TRUE
identical(replist(l1, 3), rep(list(l1), length=3))  # TRUE

答案 1 :(得分:2)

或者,您可以使用is.list():

newlist = function(x,n){ 
        if(is.list(x[[1]])) { rep(x, length=n) 
        } else { rep(list(x), length=n) }}

identical(newlist(l2,5), rep(l2, length=5)) 
identical(newlist(l1,5), rep(list(l1), length=5))
相关问题