R/misc.R

Defines functions sum.n

Documented in sum.n

#' Function to limit number of vars with missing values when calculating row sums.
#'
#' @description
#' Determining the minimum number of variables with valid values in a data frame when calculating row sums.
#'
#' @param df  \code{\link{data.frame}} with numeric variables.
#' @param n number of variables with valid values required for calculating row sums.
#' @examples
#' library(srir)
#' # all variables must have valid values for raw sums to be calculated, otherwise NA is returned.
#' sum.n(df.na[-1], 49)
#' # only 10 variables must have valid values for the sums to be calculated, otherwise NA is returned.
#' sum.n(df.na[-1], 10)
#' @export
sum.n   <- function(df, n) {
  rsum <- apply(as.matrix(df), 1, sum, na.rm = TRUE)
  nvalid <- apply(as.matrix(df), 1, function(df) sum(!is.na(df)))
  ifelse(nvalid >= n, rsum, NA)
}
NULL
nrkoehler/srir documentation built on May 23, 2019, 9:03 p.m.