gpt4 book ai didi

r - 将各因子水平输出为观星汇总统计表中的虚拟变量

转载 作者:行者123 更新时间:2023-12-04 17:47:58 26 4
gpt4 key购买 nike

我正在使用 R 包 stargazer创建高质量的回归表,我想用它来创建一个汇总统计表。我的数据中有一个因子变量,我希望汇总表显示因子在每个类别中的百分比——实际上,将因子分成一组互斥的逻辑(虚拟)变量,然后显示表中的那些。下面是一个例子:

> library(car)
> library(stargazer)
> data(Blackmore)
> stargazer(Blackmore[, c("age", "exercise", "group")], type = "text")

==========================================
Statistic N Mean St. Dev. Min Max
------------------------------------------
age 945 11.442 2.766 8.000 17.920
exercise 945 2.531 3.495 0.000 29.960
------------------------------------------

但我试图获得一个额外的行,显示每组中的百分比(在这些数据中,% 控制和/或 % 患者)。我确定这只是观星者某个地方的一个选项,但我找不到它。有谁知道它是什么?

编辑: car::Blackmoor已将拼写更新为 car::Blackmore .

最佳答案

由于 Stargazer 无法直接执行此操作,因此您可以创建自己的汇总表作为数据框并使用 pander、xtable 或任何其他包进行输出。例如,以下是如何使用 dplyr 和 tidyr 创建汇总表:

library(dplyr)
library(tidyr)

fancy.summary <- Blackmoor %>%
select(-subject) %>% # Remove the subject column
group_by(group) %>% # Group by patient and control
summarise_each(funs(mean, sd, min, max, length)) %>% # Calculate summary statistics for each group
mutate(prop = age_length / sum(age_length)) %>% # Calculate proportion
gather(variable, value, -group, -prop) %>% # Convert to long
separate(variable, c("variable", "statistic")) %>% # Split variable column
mutate(statistic = ifelse(statistic == "length", "n", statistic)) %>%
spread(statistic, value) %>% # Make the statistics be actual columns
select(group, variable, n, mean, sd, min, max, prop) # Reorder columns

如果您使用 pander 会导致这种情况:
library(pander)

pandoc.table(fancy.summary)

------------------------------------------------------
group variable n mean sd min max prop
------- ---------- --- ------ ----- ----- ----- ------
control age 359 11.26 2.698 8 17.92 0.3799

control exercise 359 1.641 1.813 0 11.54 0.3799

patient age 586 11.55 2.802 8 17.92 0.6201

patient exercise 586 3.076 4.113 0 29.96 0.6201
------------------------------------------------------

关于r - 将各因子水平输出为观星汇总统计表中的虚拟变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26912957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com