Bruce
Bruce

Reputation: 113

delete tibble from list when it has zero rows and n() columns

So I have a script that produces a set of lists as an output. For the first time it has produced a tibble in one list that has zero rows:

(testlist[[2]] in image)

and this has stopped the process going forward.

I have a found several threads about remove an empty tibble or similar when they is some action associated with the tibble or list and have tried to extract several of the filter sections of the suggestions for just the removing the tibble part and several have run, but none have worked.

All I want to do is remove any tibble with "0 rows" from my lists. In this case, testlist[[2]] from the list. I know this has to be embarrassingly simple but I am stuck.

enter image description here

Upvotes: 0

Views: 550

Answers (3)

akrun
akrun

Reputation: 887531

An option with keep

library(purrr)
keep(testlist, ~ nrow(.x) > 0)

Upvotes: 2

rjen
rjen

Reputation: 1972

An option using purrr::map_lgl.

library(purrr)

tblList[map_lgl(tblList, ~ nrow(.) != 0)]

# [[1]]
# # A tibble: 1 x 1
#         x
#     <dbl>
#   1     1
# 
# [[2]]
# # A tibble: 1 x 1
#         x
#     <dbl>
#   1     2

Data

tblList <- list(structure(list(x = 1), row.names = c(NA, -1L), class = c("tbl_df", 
"tbl", "data.frame")), structure(list(x = numeric(0)), row.names = integer(0), class = c("tbl_df", 
"tbl", "data.frame")), structure(list(x = 2), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame")))

Upvotes: 3

r2evans
r2evans

Reputation: 160607

list_of_mtcars <- list(mtcars[1,], mtcars[1:2,], mtcars[0,])
list_of_mtcars
# [[1]]
#           mpg cyl disp  hp drat   wt  qsec vs am gear carb
# Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4
# [[2]]
#               mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
# [[3]]
#  [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
# <0 rows> (or 0-length row.names)

Filter(nrow, list_of_mtcars)
# [[1]]
#           mpg cyl disp  hp drat   wt  qsec vs am gear carb
# Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4
# [[2]]
#               mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4

Upvotes: 1

Related Questions