View source: R/dataframe_tools.R
drop_empty_rows | R Documentation |
Deletes rows from a dataframe if they are 'empty'. A row is empty when every single
cell is NA
, NULL
, ""
, or matches a regular expression.
drop_empty_rows(
df,
from = 1,
to = NULL,
cols = NULL,
regex = "^$",
report = FALSE
)
df |
(Dataframe) A dataframe. |
from, to |
(Numeric or |
cols |
(Numeric or |
regex |
(Character) A regex pattern that matches a value that should be considered 'empty'. |
report |
(Logical) If |
A subset of df
with all empty rows removed.
Desi Quintans (http://www.desiquintans.com)
data <- data.frame(name = c("Jim", "Jane", "Janice", "Joe", "Jay"),
a = c(0, "", 1, NA, 0),
b = c(1, "", 1, NA, 0),
c = c(1, NA, 2, 0, 0),
d = c(0, NA, 4, 0, 0),
e = c(0, "", 5, 0, 0),
f = c(3, "", 0, 0, 0),
stringsAsFactors = FALSE)
data
#> name a b c d e f
#> 1 Jim 0 1 1 0 0 3
#> 2 Jane NA NA
#> 3 Janice 1 1 2 4 5 0
#> 4 Joe <NA> <NA> 0 0 0 0
#> 5 Jay 0 0 0 0 0 0
drop_empty_rows(data)
# Returns the whole dataframe because column 1 ('name') is never empty.
#> name a b c d e f
#> 1 Jim 0 1 1 0 0 3
#> 2 Jane NA NA
#> 3 Janice 1 1 2 4 5 0
#> 4 Joe <NA> <NA> 0 0 0 0
#> 5 Jay 0 0 0 0 0 0
drop_empty_rows(data, from = 2)
# We get the desired result when 'name' is omitted.
#> name a b c d e f
#> 1 Jim 0 1 1 0 0 3
#> 3 Janice 1 1 2 4 5 0
#> 4 Joe <NA> <NA> 0 0 0 0
#> 5 Jay 0 0 0 0 0 0
drop_empty_rows(data, from = 2, regex = "^0$")
# Regex can be used to match cells that should be 'empty'.
#> name a b c d e f
#> 1 Jim 0 1 1 0 0 3
#> 3 Janice 1 1 2 4 5 0
drop_empty_rows(data, cols = c(2, 6))
# Non-contiguous columns can be selected with 'cols'.
#> name a b c d e f
#> 1 Jim 0 1 1 0 0 3
#> 3 Janice 1 1 2 4 5 0
#> 4 Joe <NA> <NA> 0 0 0 0
#> 5 Jay 0 0 0 0 0 0
drop_empty_rows(data, cols = c(2, 6), report = TRUE)
#> Dropped rows: 1 in total
#> name a b c d e f
#> 1 Jim 0 1 1 0 0 3
#> 3 Janice 1 1 2 4 5 0
#> 4 Joe <NA> <NA> 0 0 0 0
#> 5 Jay 0 0 0 0 0 0
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.