代码之家  ›  专栏  ›  技术社区  ›  Maiasaura

如何从列表中删除空数据帧?

r
  •  17
  • Maiasaura  · 技术社区  · 16 年前

    我需要通过一个函数推送每个列表,但当它看到一个空的数据帧时,就会阻塞。那么我该如何编写一个函数来获取一个列表,对每个元素(即数据帧)进行dim,如果是0,则跳到下一个。

    我试过这样的方法:

    empties <- function (mlist)
    {
     for(i in 1:length(mlist))
       {
        if(dim(mlist[[i]])[1]!=0) return (mlist[[i]])
        }
    }
    

    但很明显,这不管用。我会在这一点上手动做这件事,但这将需要永远。救命啊?

    2 回复  |  直到 16 年前
        1
  •  26
  •   brentonk    16 年前

    mlist 如果要在运行函数之前只包含非空数据帧,请重试 mlist[sapply(mlist, function(x) dim(x)[1]) > 0]

    例如。:

    R> M1 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))
    R> M2 <- data.frame(matrix(nrow = 0, ncol = 0))
    R> M3 <- data.frame(matrix(9:12, nrow = 2, ncol = 2))
    R> mlist <- list(M1, M2, M3)
    R> mlist[sapply(mlist, function(x) dim(x)[1]) > 0]
    [[1]]
      X1 X2
    1  1  3
    2  2  4
    
    [[2]]
      X1 X2
    1  9 11
    2 10 12
    
        2
  •  15
  •   Harlan    16 年前

    sapply/索引组合的更简单、更透明的方法是使用Filter()函数:

    > Filter(function(x) dim(x)[1] > 0, mlist)
    [[1]]
      X1 X2
    1  1  3
    2  2  4
    
    [[2]]
      X1 X2
    1  9 11
    2 10 12
    
        3
  •  7
  •   Ronak Shah    7 年前

    而不是 dim(x)[1] 你可以利用 nrow ,所以你可以

    mlist[sapply(mlist, nrow) > 0]
    
    Filter(function(x) nrow(x) > 0, mlist)
    

    你也可以用 keep discard purrr

    purrr::keep(mlist, ~nrow(.) > 0)
    purrr::discard(mlist, ~nrow(.) == 0)
    

    还有 compact 呼噜声 直接删除所有空元素。它是一个包装纸

    purrr::compact(mlist)
    

    nrow公司 具有 ncol 在上述答案中。此外,您还可以使用 lengths

    mlist[lengths(mlist) > 0]
    
        4
  •  1
  •   cephalopod    7 年前

    添加tidyverse选项:

    library(tidyverse)
    mlist[map(mlist, function(x) dim(x)[1]) > 0]
    
    
    mlist[map(mlist, ~dim(.)[1]) > 0]