Reputation: 4229
I have list of dataframes and some are empty, how can I remove these?
$`S566X7221`
[1] V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26
<0 rows> (or 0-length row.names)
I have tried these, but non of them work
x[lapply(x,length)>0]
Filter(length, x)
Upvotes: 11
Views: 5438
Reputation: 18742
list_drop_empty()
from the vctrs
package will drop any empty element from a list, including NULL
:
library(vctrs)
x <- list(w = data.frame(a = 1), x = NULL, y = logical(), z = data.frame(a = numeric(), b = character()))
list_drop_empty(x)
# $w
# a
# 1 1
Upvotes: 0
Reputation: 44575
You're close. But you want nrow
, not length
(which is actually the number of columns in a data.frame).
x <- list(data.frame(A=numeric(),B=numeric()), data.frame(A=1:3, B=4:6), data.frame(A=1,B=2))
x[sapply(x, nrow)>0]
Before:
> x
[[1]]
[1] A B
<0 rows> (or 0-length row.names)
[[2]]
A B
1 1 4
2 2 5
3 3 6
[[3]]
A B
1 1 2
After:
> x[sapply(x, nrow)>0]
[[1]]
A B
1 1 4
2 2 5
3 3 6
[[2]]
A B
1 1 2
Upvotes: 17