我有一个带有原始分数和样本权重的数据文件。现在,我要在考虑样本权重的情况下使用心理软件包的describe函数。
有人知道怎么做,还是某个地方的功能与psych :: describe()完全相同,但可以处理样本权重?
下一个示例将对我打算做什么有所了解。
library(psych)
describe(c(2,3,4,1,4,5,3,3))
#gives:
vars n mean sd median trimmed mad min max range skew kurtosis se
1 1 8 3.12 1.25 3 3.12 1.48 1 5 4 -0.2 -1.16 0.44
样本权重为:
c(0.2,0.5,1.2,1.5,0.2,0.6,0.6,1.1)
加权平均值将是(如果我错了,请纠正我):
sum(c(2,3,4,1,4,5,3,3)* c(0.2,0.5,1.2,1.5,0.2,0.6,0.6,1.1))/sum(c(0.2,0.5,1.2,1.5,0.2,0.6,0.6,1.1))
[1] 2.898305
因此,这当然与未加权平均值不同。如何确保报告的SD,峰度,偏度等也基于样本加权平均值?
由于psych软件包不处理权重,并且没有替代的软件包可以提供等效的加权描述,因此必须像psych::describe()
那样从不同的软件包中挑选并组合输出。
此外,通常需要在数据中为每种情况提供加权描述的计算以及为这些情况分配的各个权重,因此“快捷方式”将不起作用。 (例如,加权标准误差将not等于加权标准偏差除以样本大小的平方根。)
这是一个简单的包装函数,它模拟加权数据的psych::describe()
行为:
wtd.describe <- function(x, weights=NULL, trim=.1){
require(TAM)
require(diagis)
require(robsurvey)
out <- NULL
# Handling simple vectors
x <- as.data.frame(x)
# If no weights given, all weights = 1
if(is.null(weights)) {weights <- seq(1, nrow(x))}
i <- 1
for(colname in colnames(x)){
# Removing rows with missing data or weight
d <- x[complete.cases(x[[colname]], weights), , drop=FALSE][[colname]]
w <- weights[complete.cases(x[[colname]], weights)]
wd <- data.frame(
"vars" = i,
"n" = length(d),
"mean" = TAM::weighted_mean(d, w = w),
"sd" = TAM::weighted_sd(d, w = w),
"median" = robsurvey::weighted_median(d, w = w, na.rm = TRUE),
"trimmed" = robsurvey::weighted_mean_trimmed(d, w = w, LB = trim, UB = (1 - trim), na.rm = TRUE),
"mad" = robsurvey::weighted_mad(d, w = w, na.rm = TRUE, constant = 1.4826),
"min" = min(d),
"max" = max(d),
"range" = max(d) - min(d),
"skew" = TAM::weighted_skewness(d, w = w),
"kurtosis" = TAM::weighted_kurtosis(d, w = w),
"se" = diagis::weighted_se(d, w = w, na.rm = TRUE),
row.names = colname
)
i <- i+1
out <- rbind(out, wd)
}
return(out)
}
请注意:
psych:describe()
的大多数便利参数未由上述功能仿真。