nobs: Compute the Number of Non-Missing Observations

View source: R/nobs.R

nobsR Documentation

Compute the Number of Non-Missing Observations

Description

Compute the number of non-missing observations. Provides a new default method to handle numeric and logical vectors, and a method for data frames.

Usage

nobs(object, ...)
## Default S3 method:
nobs(object, ...)
## S3 method for class 'data.frame'
nobs(object, ...)
## S3 method for class 'lm'
nobs(object, ...)
n_obs(object, ...)

Arguments

object

Numeric or logical vector, data frame, or a model object.

...

Further arguments to be passed to methods.

Value

Either single numeric value (for vectors) or a vector of numeric values (for data frames) giving the number of non-missing values.

Note

The base R package stats provides a generic nobs function with methods for fitted model objects. The gdata package adds methods for numeric and logical vectors, as well as data frames.

An alias function n_obs is also provided, equivalent to gdata::nobs. Using n_obs in scripts makes it explicitly clear that the gdata implementation is being used.

Author(s)

Gregory R. Warnes greg@warnes.net

See Also

nobs in package 'stats' for the base R implementation, is.na, length

Examples

x <- c(1, 2, 3, 5, NA, 6, 7, 1, NA)
length(x)
nobs(x)

df <- data.frame(x=rnorm(100), y=rnorm(100))
df[1,1] <- NA
df[1,2] <- NA
df[2,1] <- NA
nobs(df)

fit <- lm(y~x, data=df)
nobs(fit)
n_obs(fit)

# Comparison
# gdata
nobs(x)
nobs(df)
# stats
length(na.omit(x))
sapply(df, function(x) length(na.omit(x)))

warnes/gdata documentation built on Dec. 5, 2023, 12:20 a.m.