Fast (Grouped) Observation Count for Matrix-Like Objects
Fast (Grouped) Observation Count for Matrix-Like Objects
fnobs is a generic function that (column-wise) computes the number of non-missing values in x, (optionally) grouped by g. It is much faster than sum(!is.na(x)). The TRA argument can further be used to transform x using its (grouped) observation count.
fnobs(x,...)## Default S3 method:fnobs(x, g =NULL, TRA =NULL, use.g.names =TRUE,...)## S3 method for class 'matrix'fnobs(x, g =NULL, TRA =NULL, use.g.names =TRUE, drop =TRUE,...)## S3 method for class 'data.frame'fnobs(x, g =NULL, TRA =NULL, use.g.names =TRUE, drop =TRUE,...)## S3 method for class 'grouped_df'fnobs(x, TRA =NULL, use.g.names =FALSE, keep.group_vars =TRUE,...)
Arguments
x: a vector, matrix, data frame or grouped data frame (class 'grouped_df').
g: a factor, GRP object, atomic vector (internally converted to factor) or a list of vectors / factors (internally converted to a GRP object) used to group x.
use.g.names: logical. Make group-names and add to the result as names (default method) or row-names (matrix and data frame methods). No row-names are generated for data.table's.
drop: matrix and data.frame method: Logical. TRUE drops dimensions and returns an atomic vector if g = NULL and TRA = NULL.
keep.group_vars: grouped_df method: Logical. FALSE removes grouping variables after computation.
...: arguments to be passed to or from other methods. If TRA is used, passing set = TRUE will transform data by reference and return the result invisibly.
Details
fnobs preserves all attributes of non-classed vectors / columns, and only the 'label' attribute (if available) of classed vectors / columns (i.e. dates or factors). When applied to data frames and matrices, the row-names are adjusted as necessary.
Returns
Integer. The number of non-missing observations in x, grouped by g, or (if TRA is used) x transformed by its number of non-missing observations, grouped by g.
See Also
fndistinct, Fast Statistical Functions , Collapse Overview
Examples
## default vector methodfnobs(airquality$Solar.R)# Simple Nobsfnobs(airquality$Solar.R, airquality$Month)# Grouped Nobs## data.frame methodfnobs(airquality)fnobs(airquality, airquality$Month)fnobs(wlddev)# Works with data of all types!head(fnobs(wlddev, wlddev$iso3c))## matrix methodaqm <- qM(airquality)fnobs(aqm)# Also works for character or logical matricesfnobs(aqm, airquality$Month)## method for grouped data frames - created with dplyr::group_by or fgroup_byairquality |> fgroup_by(Month)|> fnobs()wlddev |> fgroup_by(country)|> fselect(PCGDP,LIFEEX,GINI,ODA)|> fnobs()