Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty zero length rows in list with R

Tags:

r

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)
like image 508
Maximilian Avatar asked May 21 '14 10:05

Maximilian


1 Answers

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
like image 66
Thomas Avatar answered Oct 17 '22 09:10

Thomas