This function calculates the sample variance for each row of a numeric matrix or data frame. It uses the standard sample variance formula with Bessel's correction (dividing by n-1).
Arguments
- x
A numeric matrix or data frame for which row variances are to be calculated.
- na.rm
A logical value indicating whether missing values (NA) should be removed before calculating variances. If
TRUE
(default), missing values are excluded and the denominator is adjusted accordingly. IfFALSE
, any row containing missing values will result inNA
.
Value
A numeric vector of length equal to the number of rows in x
,
containing the sample variance for each row.
Details
The function computes sample variances using the formula: $$\sigma^2 = \frac{\sum_{i=1}^{n}(x_i - \bar{x})^2}{n-1}$$
When na.rm = TRUE
, the function:
Excludes missing values from mean and variance calculations
Adjusts the degrees of freedom (n-1) based on the number of non-missing values in each row
Returns
NaN
for rows with fewer than 2 non-missing values
When na.rm = FALSE
, the function:
Uses all values including missing ones
Returns
NA
for any row containing missing valuesUses
ncol(x) - 1
as the degrees of freedom
Examples
if (FALSE) { # \dontrun{
# Basic usage with a matrix
mat <- matrix(1:12, nrow = 3)
rowVars(mat)
# With missing values
mat[1, 2] <- NA
mat[2, 3] <- NA
rowVars(mat, na.rm = TRUE) # Excludes NAs
rowVars(mat, na.rm = FALSE) # Includes NAs (returns NA for affected rows)
# With a data frame
df <- data.frame(
a = c(1, 4, 7),
b = c(2, 5, 8),
c = c(3, 6, 9)
)
rowVars(df)
# Edge case: single column (variance is 0)
single_col <- matrix(1:3, ncol = 1)
rowVars(single_col) # Returns NaN due to division by 0
} # }