【发布时间】:2021-03-15 23:37:32
【问题描述】:
我想创建一个名为 Label 的列以显示在我的汇总统计信息中。例如,如下表所示。
假设我有这个数据框:
df <- data.frame(age_years = c(33, 11, 45, 67, 8, 99), sex = factor(c(0, 1, 1, 0, 0, 0)))
> df
age_years sex
1 33 0
2 11 1
3 45 1
4 67 0
5 8 0
6 99 0
我尝试使用Hmisc 包。
library(Hmisc)
var.labels = c(age_years="Age in Years", sex="Sex")
label(df) = as.list(var.labels[match(names(df), names(var.labels))])
对于汇总表,我使用了以下代码:
Variables <- names(df)
Label <- label(df)
Missing <- sapply(df, function(x) sum(is.na(x)))
Type <- sapply(df, function(x) class(x))
Min <- sapply(df, function(x) min(x, na.rm = TRUE))
Max <- sapply(df, function(x) max(x, na.rm = TRUE))
SD <- sapply(df, function(x) format(round(sd(x, na.rm=TRUE), 2), nsmall = 2))
Mean <- sapply(df, function(x) format(round(mean(x, na.rm=TRUE), 2), nsmall = 2))
#To get the Latex table for the rows
knitr::kable(as.data.frame(cbind(Variables, Label, Missing, Type, Min, Max, Mean, SD), row.names = FALSE), "latex")
我没有使用上述代码获得名为“标签”的列。我想在汇总统计表的标签列中将变量 age_years 标记为“年龄”,而性别变量也是如此。我从 R 得到这个乳胶输出。
\begin{tabular}{l|l|l|l|l|l|l|l}
\hline
Variables & Missing & age\_years & sex & Min & Max & Mean & SD\\
\hline
age\_years & 0 & labelled & labelled & 0 & 104 & 54.94 & 20.06\\
\hline
sex & 0 & numeric & numeric & 1 & 2 & 1.46 & 0.50\\
\hline
\end{tabular}
我的 Latex 表看起来不像上面那个:
我不确定为什么 age_years 和 sex 显示为列。我想摆脱这些可变列。
我觉得这部分代码有问题Label <- label(df)
【问题讨论】: