我有以下示例数据:
ID GLUC TGL HDL LDL HRT MAMM SMOKE
A 88 NA 32 99 Y NA never
B NA 150 60 NA NA no never
C 110 NA NA 120 N NA NA
D NA 200 65 165 NA yes never
我需要编写一个用于数字变量的函数,计算均值,中位数,STD并计算缺失值(NMiss)的数量。对于字符变量,我需要将变量每个级别的计数表制成表格,并计算缺失值的数量。
我想要的结果是一个长度为2的列表。列表的每个组成部分都是包含统计信息的数据框或NULL值,如下所示:
table1 (dat=patient, numvar=c("TGL", "HDL", "LDL"),
charvar=c("HRT", "MAMM"))
$numericStats
varName MEAN MEDIAN SD NMiss
TGL 180.66667 180.0 23.03620 4
HDL 55.66667 62.5 19.00175 4
LDL 160.28571 165.0 40.06126 3
$FactorStats
varName group count
HRT N 2
Y 3
NMiss 5
MAMM no 2
yes 4
NMiss 4
我到目前为止所拥有的功能:
table1 <- function(dat, varlist){
if (!all(is.element(varlist, names(dat))))
stop ("One or more of the variables are not in the data.")
result <- matrix(numeric(length(varlist)*5), nrow = length(varlist))
for (i in 1:length(varlist)){
var_select <- dat[[varlist[i]]]
mean_value <- round(mean(var_select, na.rm=T),2)
median_value = round(median(var_select, na.rm=T),2)
SD <- round(sd(var_select, na.rm=T),2)
N <- length(var_select[!is.na(var_select)])
N_miss <- length(var_select[is.na(var_select)])
result[i,] <- c(mean_value, median_value, SD, N, N_miss) + }
colnames(result) <- c("Mean", "Median", "SD", "N", "N_miss")
rownames(result) <- varlist
return(result)
}
我不知道如何在我的职能中包括分类因素。任何帮助将不胜感激。