简体   繁体   中英

rep() first level of lists

I wish to expand lists to a given length using rep() , as in:

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

However, my lists come in two flavours, nested or not nested:

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

To deal with this problem I probably need to identify the problematic l1 as being "first-level" and wrap it into list() before applying rep() . What is the best way to do this?

Here is an idea:

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

Or, you could use 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM