rapply to nested list of data frames in R

后端 未结 3 918
太阳男子
太阳男子 2020-12-20 14:48

i have a nested list whose fundamental element is data frames, and i want to traverse this list recursively to do some computation of each data frame, finally to get a neste

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 15:49

    Handling list computation at a specific depth:

    recursive_lapply <- function (data, fun, depth = 1L) {
      stopifnot(inherits(data, "list"))
      stopifnot(depth >= 1)
      f <- function(data, fun, where = integer()) {
        if (length(where) == depth) {
          fun(data)
        } else {
          res <- lapply(seq_along(data), function(i) {f(data[[i]], fun, where = c(where, i))})
          names(res) <- names(data)
          res
        }
      }
      f(data, fun)
    }
    

    example computation:

    d <- list(
      A = list(a = list(
        a1 = data.table::data.table(x = 11:15, y = 10:14),
        a2 = data.table::data.table(x = 1:5, y = 0:4)
      )),
      B = list(b = list(
        b1 = data.table::data.table(x = 7, y = 8),
        b2 = data.table::data.table(x = 9, y = 10)
      ))
    )
    
    > recursive_lapply(d, function(data) data[, "z":= x + y], 3)
    $A
    $A$a
    $A$a$a1
        x  y  z
    1: 11 10 21
    2: 12 11 23
    3: 13 12 25
    4: 14 13 27
    5: 15 14 29
    
    $A$a$a2
       x y z
    1: 1 0 1
    2: 2 1 3
    3: 3 2 5
    4: 4 3 7
    5: 5 4 9
    
    $B
    $B$b
    $B$b$b1
       x y  z
    1: 7 8 15
    
    $B$b$b2
       x  y  z
    1: 9 10 19
    

提交回复
热议问题