Question

I have a list with every entry is a data.frame. I have also written a function that tries to weed out data.frames which have zero rows:

delete_zeroes <- function(data){
  if(nrow(data) == 0){
    return(NULL)
  }  
  (data)
}

llply(data, delete_zeroes)

However, this simply seems to place NULL on entries that match. I would like to completely get rid of each matching entry. How can I accomplish this?

Was it helpful?

Solution

You could use a logical index to exclude every item with a data.frame that has no rows:

# example data
l <- list(a=data.frame(a=1:3), b=data.frame(), c=data.frame(a=1:3))
# $a
#   a
# 1 1
# 2 2
# 3 3
# 
# $b
# data frame with 0 columns and 0 rows
# 
# $c
#   a
# 1 1
# 2 2
# 3 3

nr <- sapply(l, nrow)
# a b c 
# 3 0 3 

l <- l[nr > 0]
# $a
#   a
# 1 1
# 2 2
# 3 3
#
# $c
#   a
# 1 1
# 2 2
# 3 3

OTHER TIPS

Try the following:

Filter(nrow, data)

You can try

sapply(LL, nrow) will give you vector with number of rows in each data.frame in the list. You compare that with 0 to get logical vector to be used as index for subsetting the list

LL <- list(data.frame(1:2), data.frame(), data.frame(3:4))
##  [[1]]
##    X1.2
##  1    1
##  2    2

##  [[2]]
##  data frame with 0 columns and 0 rows

##  [[3]]
##    X3.4
##  1    3
##  2    4

LL[sapply(LL, nrow) != 0]

##  [[1]]
##    X1.2
##  1    1
##  2    2

##  [[2]]
##    X3.4
##  1    3
##  2    4    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top