Skip to contents

Keeps rows/columns in an array-like object using a predicate function.

Usage

keep(x, f, ...)

keep_cols(x, f, ...)

keep_rows(x, f, ...)

# S4 method for ANY,`function`
keep(x, f, margin = 1, negate = FALSE, all = FALSE)

# S4 method for ANY,`function`
keep_rows(x, f, negate = FALSE, all = FALSE)

# S4 method for ANY,`function`
keep_cols(x, f, negate = FALSE, all = FALSE)

Arguments

x

An object (should be a matrix or a data.frame).

f

A predicate function.

...

Currently not used.

margin

A vector giving the subscripts which the function will be applied over (1 indicates rows, 2 indicates columns).

negate

A logical scalar: should the negation of f be used instead of f?

all

A logical scalar. If TRUE, only the rows/columns whose values all meet the condition defined by f are considered. If FALSE (the default), only rows/columns where at least one value validates the condition defined by f are considered.

See also

Other data cleaning tools: compact(), count(), detect(), discard(), infinite, missing, zero

Author

N. Frerebeau

Examples

## Create a count data matrix
X <- matrix(sample(1:10, 25, TRUE), nrow = 5, ncol = 5)

## Add NA
k <- sample(1:25, 3, FALSE)
X[k] <- NA
X
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]   10    4   10    4   10
#> [2,]    9    9    5    9    6
#> [3,]   NA   NA    5    5    8
#> [4,]    1    2    7    8    5
#> [5,]   NA    1    6    9    5

## Count missing values in rows
count(X, f = is.na, margin = 1)
#> [1] 0 0 2 0 1
## Count non-missing values in columns
count(X, f = is.na, margin = 2, negate = TRUE)
#> [1] 3 4 5 5 5

## Find row with NA
detect(X, f = is.na, margin = 1)
#> [1] FALSE FALSE  TRUE FALSE  TRUE
## Find column without any NA
detect(X, f = is.na, margin = 2, negate = TRUE, all = TRUE)
#> [1] FALSE FALSE  TRUE  TRUE  TRUE

## Keep row without any NA
keep(X, f = is.na, margin = 1, negate = TRUE, all = TRUE)
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]   10    4   10    4   10
#> [2,]    9    9    5    9    6
#> [3,]    1    2    7    8    5
## Keep row without any NA
keep(X, f = is.na, margin = 2, negate = TRUE, all = TRUE)
#>      [,1] [,2] [,3]
#> [1,]   10    4   10
#> [2,]    5    9    6
#> [3,]    5    5    8
#> [4,]    7    8    5
#> [5,]    6    9    5

## Remove row with any NA
discard(X, f = is.na, margin = 1, all = FALSE)
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]   10    4   10    4   10
#> [2,]    9    9    5    9    6
#> [3,]    1    2    7    8    5
## Remove column with any NA
discard(X, f = is.na, margin = 2, all = FALSE)
#>      [,1] [,2] [,3]
#> [1,]   10    4   10
#> [2,]    5    9    6
#> [3,]    5    5    8
#> [4,]    7    8    5
#> [5,]    6    9    5

## Replace NA with zeros
replace_NA(X, value = 0)
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]   10    4   10    4   10
#> [2,]    9    9    5    9    6
#> [3,]    0    0    5    5    8
#> [4,]    1    2    7    8    5
#> [5,]    0    1    6    9    5