If prices and quantities are available, expenditure shares (weights) can be derived by region and/or product. This function may be used in cpd(), nlcpd() and prices().
shares <- function(p, q, r=NULL, n=NULL){
# input checks:
.check.num(x=p, int=c(0, Inf))
.check.num(x=q, int=c(0, Inf))
.check.char(x=r, miss.ok=TRUE, null.ok=TRUE)
.check.char(x=n, miss.ok=TRUE, null.ok=TRUE)
.check.lengths(x=p, y=q)
.check.lengths(x=p, y=r)
.check.lengths(x=p, y=n)
# shares across all observations:
if(is.null(r) && is.null(n)){
s <- p*q/sum(p*q, na.rm=TRUE)
}
# shares by region:
if(!is.null(r) && is.null(n)){
s <- (p*q)/ave(x=p*q, r, FUN=function(z) sum(z, na.rm=TRUE))
}
# shares by product:
if(is.null(r) && !is.null(n)){
s <- (p*q)/ave(x=p*q, n, FUN=function(z) sum(z, na.rm=TRUE))
}
# shares by product and region, should result in a vector of ones:
if(!is.null(r) && !is.null(n)){
s <- (p*q)/ave(x=p*q, r, n, FUN=function(z) sum(z, na.rm=TRUE))
}
# return output:
return(s)
}
No implementation. Function is not needed as this can be easily solved by
dt[, p*q / sum(p*q, na.rm=TRUE), by="region"]
or
dt[, p*q / sum(p*q, na.rm=TRUE)]
If prices and quantities are available, expenditure shares (weights) can be derived by region and/or product. This function may be used in
cpd()
,nlcpd()
andprices()
.