View source: R/R05-Statistical_tools.R
camr_statistic | R Documentation |
A function for flexible and robust computation of univariate
statistics over a vector of observations. Can be combined
with the dplyr::group_by()
and
dplyr::summarise()
functions from
the package 'dplyr'.
camr_statistic(
x,
f = length,
include = NULL,
exclude = NULL,
na.rm = TRUE,
default = NA,
...
)
x |
A vector. |
f |
A function that computes a univariate statistc
(e.g., |
include |
Optional logical vector of matching length
to |
exclude |
Optional vector of types of observations in
|
na.rm |
Logical; if |
default |
The default value to return in the case of missing data (i.e., no observation over which to compute a statistic). |
... |
Additional parameters for the function |
A univariate statistic, or the default value.
Kevin Potter
# Load in base R data set
data( iris )
# Sepal length
sln <- iris$Sepal.Length
# Number of observations for sepal length
camr_statistics( sln )
# Mean sepal length
camr_statistics( sln, f = mean )
# Define custom function for formatted mean
f_x <- function(x) as.character( round( mean(x), 2 ) )
camr_statistics( sln, f = f_x )
# Petal length
pln <- iris$Petal.Length
# Conditional mean for sepal length when petal length < 3.5
camr_statistics( sln, f = f_x, include = pln < 3.5 )
# Species of iris
spc <- iris$Species
# Isolate species 'virginica'
vrg <- spc == 'virginica'
# No petal lengths less than 3.5 for virginica, so return default
camr_statistics(
sln[vrg], f = f_x, include = pln[vrg] < 3.5, default = 'No obs'
)
# Compute percentage of species 'setosa'
f_p <- function(x) paste0( round( 100*mean(x == 'setosa') ), '%' )
camr_statistics( spc, f = f_p )
# Exclude 'virginica'
camr_statistics( spc, f = f_p, exclude = 'virginica' )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.