mands {lazy.tools} | R Documentation |
Calculates mean, std, variance and n with case weight
mands(data, weight = 1, probs = NULL, by = NULL, byvarname = NULL, vardef = "n", print = 0, simplify = 1)
data |
data vector, matrix or data frame. |
weight |
case weight vector of length nrow(data) or 1. |
probs |
vector of probabilities to calculate quantiles |
by |
a factor or a list of factors, each of length nrow(data) |
byvarname |
vector containing the names of by varialbes to be used. (Not Yet Implemented.) |
vardef |
= "n-1" to use n-1 as denominator for variance. |
print |
= 1 to print the result |
simplify |
= 0 to return class by object when by= is given. |
The quantiles will be calculated using wquantile function in this package.
A matrix of statistics(mean, std, var, nobs, n) x variables:
where nobs is sum(weights) for nonmissing obs, and n is nrow(data).
In addition, if probs
is given, quantiles will be appended to
the above.
When by is present, it returns a class by object consisting of above
for each subgroup if simplify=0.
If by is not a list and simplify=1,
the result is a statistics x variables x subgroups array.
If by is a list of several factors, simplify=1 does not affet the result.
When X is univariate, the result is a statistics x subgroup matrix.
When data is NULL, NULL will be returned.
# univariate example y <- 1:9 pdf <- exp( -0.5*(y-5)^2/(1.3^2) ) pdf <- pdf/sum(pdf) group <- c(1,1,1,1,1,2,2,2,2) mands( y ) mands( y, pdf ) mands( y, by=group ) # bivariate example ndims <- 2; npoints <- 11; xmin <- -3; xmax <- 3; corrmat <- 0.2 nobs <- 100000 # dispersion matrix Dmat <- matrix(corrmat,ndims,ndims)+(1-corrmat)*diag(ndims) Dmat[1,1] <- .5 # grid X X <- seq(xmin,xmax,length.out=npoints) if( ndims >= 2 ){ for( i in 2:ndims ) X <- cprod(X,seq(xmin,xmax,length.out=npoints)) } # weight pdf <- exp( -0.5*diag( X%*%solve(Dmat)%*%t(X)) ) pdf <- pdf/sum(pdf) freq <- round(nobs*pdf+.5) # all data mands( X ) mands( X, freq ) mands( X, freq, probs=c(0.25,0.5,0.75,0.975) ) # grouping variable set.seed(1701) if( is.matrix(X) ) n <- nrow(X) else n <- length(X) byvar <- sample(1:3, n, replace=1) byvar <- sort(byvar) # for each subgroup mands( X, by=byvar ) mands( X, freq, by=byvar ) mands( X, freq, by=byvar, probs=c(0.25,0.75) )