Skip to content

rowMeans and friends with na.rm = TRUE still count the NA cells #1

Open

Description

@buyan-kh

when a matrix has a stored NA value, rowMeans, colMeans, rowVars, colVars, rowSds and colSds with na.rm = TRUE skip the NA in the sum but still divide by the full row or column length. so the answer comes out too small and doesn't match base R or matrixStats.

small repro:

m <- matrix(c(1, 0, 3, 4,
              2, 2, NA, 0,
              0, 5, 1, 1), nrow = 3, byrow = TRUE,
            dimnames = list(idx1 = paste0("r", 1:3), idx2 = paste0("c", 1:4)))
df <- do.call(expand.grid, c(dimnames(m), stringsAsFactors = FALSE))
df$value <- as.vector(m)
df <- df[is.na(df$value) | df$value != 0, ]
tf <- tempfile(fileext = ".parquet")
arrow::write_parquet(df, tf)
x <- as(DuckDBArray(tf, datacol = "value", keycols = dimnames(m)), "DuckDBMatrix")

rowMeans(x, na.rm = TRUE)[2]  # 1, base R gives 1.333333
colMeans(x, na.rm = TRUE)[3]  # 1.333333, base R gives 2

the variances and sds are off the same way. it hasn't come up yet because the tests only use data without NA, but any matrix with a missing value will hit it.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions