从没有观察的列表中删除数据框

时间:2021-05-27 16:08:12

标签: r

我有一个数据框列表,我想从列表中删除所有没有观察到的数据框。

df.list <- list(structure(list(Date = structure(c(1621814400, 1621900800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), units = c(7,9), dollars = c(41.93, 53.91), margin = c(20.09, 25.83), margin_pct = c(0.479131,0.479131)), row.names = c(NA, -2L), class = c("tbl_df", "tbl","data.frame")), structure(list(Date = structure(c(1621641600,1621728000, 1621814400, 1621900800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), units = c(2, 4, 28, 45), dollars = c(2.78,5.56, 37.32, 59.95), margin = c(2.23, 4.46, 29.6, 47.56), margin_pct = c(0.802158,0.802158, 0.79314, 0.793327)), row.names = c(NA, -4L), class = c("tbl_df","tbl", "data.frame")), structure(list(Date = structure(numeric(0), class = c("POSIXct","POSIXt"), tzone = "UTC"), units = numeric(0), dollars = numeric(0),margin = numeric(0), margin_pct = numeric(0)), row.names = integer(0), class = c("tbl_df","tbl", "data.frame")), structure(list(Date = structure(numeric(0), class = c("POSIXct","POSIXt"), tzone = "UTC"), units = numeric(0), dollars = numeric(0),margin = numeric(0), margin_pct = numeric(0)), row.names = integer(0), class = c("tbl_df","tbl", "data.frame"))) ```

2 个答案:

答案 0 :(得分:2)

这将删除具有零行的数据框:

df.list[which(lapply(df.list, nrow) != 0)]

答案 1 :(得分:2)

我们可以为此使用 discardkeep 函数:

library(purrr)

df.list %>%
  discard(~ nrow(.x) == 0) -> df.list


[[1]]
# A tibble: 2 x 5
  Date                units dollars margin margin_pct
  <dttm>              <dbl>   <dbl>  <dbl>      <dbl>
1 2021-05-24 00:00:00     7    41.9   20.1      0.479
2 2021-05-25 00:00:00     9    53.9   25.8      0.479

[[2]]
# A tibble: 4 x 5
  Date                units dollars margin margin_pct
  <dttm>              <dbl>   <dbl>  <dbl>      <dbl>
1 2021-05-22 00:00:00     2    2.78   2.23      0.802
2 2021-05-23 00:00:00     4    5.56   4.46      0.802
3 2021-05-24 00:00:00    28   37.3   29.6       0.793
4 2021-05-25 00:00:00    45   60.0   47.6       0.793

df.list %>%
  keep(~ nrow(.x) != 0) -> df.list