rowsum2: Flexible summation of matrix/data.frame rows

View source: R/rowsum2.R

rowsum2R Documentation

Flexible summation of matrix/data.frame rows

Description

Count the sum of values, sum of zeros, or sum of NAs in the each row of a data.frame or matrix. Optionally count only certain columns and/or compare the row sums to a desired value.

Usage

rowsum2(data, x = c("na", "zero", "sum"), op, value, pattern, ...)

Arguments

data

data.frame or matrix.

x

string method, one of either: "na", "zero", or "sum".

op

Optional string describing operator to use for comparing row sums to a desired value. One of either: "==", "!=", "<=", ">=", "<", ">".

value

Optional numeric value to compare the row sums against.

pattern

Optional string containing a regular expression to match column names via grep.

...

Other arguments to be passed into grep.

Value

Returns a logical vector if 'op' and 'value' have been specified. Otherwise returns a numeric vector.

Examples

mat <- matrix(c(NA, 1:6, 0), nrow = 4, ncol = 2,
              dimnames = list(NULL, c("sample1", "sample2")))
df <- data.frame(mat)

# works with data.frame or matrix
rowsum2(mat, "na")
rowsum2(df, "na")

# get just the sums (should use rowSums directly in this particular case),
# or sum of na/zero for each row
rowsum2(mat, "sum")
rowsum2(mat, "na")
rowsum2(mat, "zero")

# compare the row sums against a value of interest to
# see which rows 'pass'
rowsum2(mat, "sum", ">", 5)

# get row sums for only certain columns based on
# matching columns with grep
rowsum2(mat, "na", pattern = "sample1")

# combine row sum comparison and column matching
rowsum2(df, "na", "==", 0, "sample1")


csdaw/csdmisc documentation built on April 26, 2022, 5:39 a.m.