Skip to contents

Compute row-wise means from a logical/numeric matrix or data.frame. Rows exceeding a specified missing-value proportion are set to NA.

Usage

rowMeans2(x, na_allowed = 0.2, round_digits = NULL)

Arguments

x

(logical/numeric matrix or data.frame)
A rectangular object whose rows will be aggregated via means. Each column must be logical or numeric.

na_allowed

(Scalar numeric: 0.2; [0, 1])
Maximum allowed proportion of missing values per row (\(\pi_i\)) before the result is set to NA. Rows with \(\pi_i > \text{na\_allowed}\) return NA; rows with \(\pi_i \le \text{na\_allowed}\) are computed.

round_digits

(NULL or scalar non-negative integer: NULL)
If not NULL, round the resulting means to the specified number of digits.

Value

A double vector of length nrow(x) containing the row-wise means, with NA where the missing proportion exceeds na_allowed. For inputs with at least one row and one column, row names are preserved. If x has zero rows, a zero-length double vector is returned. If x has zero columns, an unnamed length-nrow(x) double vector of NA is returned.

Details

Let \(p\) be the number of columns in x. For row \(i\), let \(\pi_i\) be the proportion of missing values in that row.

If \(\pi_i > \tau\) where \(\tau\) is na_allowed, the returned mean for row \(i\) is NA. Otherwise, when at least one observed value exists, the mean is computed over the observed values only:

$$M_i = \frac{1}{|\{j : x_{ij} \text{ not missing}\}|} \sum_{j: x_{ij} \text{ not missing}} x_{ij}.$$

If all entries in a row are NA or NaN, the result for that row is NA regardless of na_allowed. NaN is treated as missing because missingness is determined by base::is.na(). Inf and -Inf are treated as observed values and are passed to base::rowMeans() arithmetic. A row with both observed Inf and -Inf can therefore return NaN. Logical values are averaged as FALSE = 0 and TRUE = 1.

Rounding is disabled by default. Set round_digits to round the resulting means.

See also

Examples

#----------------------------------------------------------------------------
# rowMeans2() examples
#----------------------------------------------------------------------------
library(bkbase)

m <- matrix(
  c(1, NA, 3, 4,
    2,  5, NA, 6),
  nrow = 2,
  byrow = TRUE
)
m
#>      [,1] [,2] [,3] [,4]
#> [1,]    1   NA    3    4
#> [2,]    2    5   NA    6

# Allow up to 25% missing per row
rowMeans2(m, na_allowed = 0.25)
#> [1] 2.666667 4.333333

# Enable rounding to 2 digits
rowMeans2(m, na_allowed = 0.5, round_digits = 2)
#> [1] 2.67 4.33