原始计数和由R表中的调查权重加权的百分比?

发布于 2025-01-25 22:30:15 字数 678 浏览 3 评论 0原文

我正在使用R软件包table1来创建一个简单的摘要统计表,以用于大多数分类的变量(年龄类别,性别,种族等)。表中的计数需要是原始计数,但是数据集中的调查权重变量需要加权百分比。似乎应该有一个功能的桌面制作软件包,这似乎是一项足够简单的任务,但是我似乎无法在Table1,Flextable,GT,KableExtra或任何其他包装中找到解决方案。

下面的示例大致显示了我到目前为止能够做的事情,但是出现的百分比未加权,我找不到使用sv_weight变量来计算加权百分比的方法。

set.seed(123)
dat <- data.frame(
  year = factor(sample(c("2019", "2020"), 100, replace = TRUE)),
  sv_weight = (sample(1:150, 100, replace = TRUE)),
  sex = factor(sample(c("Male", "Female"), 100, replace = TRUE)),
  race =  factor(sample(c("White", "Hispanic", "Black"), 100, replace = TRUE)))

library(table1)
tab<- table1(~ sex + race | year, data = dat) 

tab

I'm using the R package table1 to create a simple table of summary statistics for mostly factored variables (age categories, sex, race, etc.). The counts in the table need to be raw counts, but the percentages need to be weighted by a survey weight variable in the dataset. It seems like a simple enough task that there should be a table-making package that has a function for this, but I can't seem to find a solution in table1, flextable, gt, kableExtra, or any other package.

The example below shows roughly what I've been able to do so far, but the percentages that appear are unweighted and I can't find a way to use the sv_weight variable to calculate weighted percentages.

set.seed(123)
dat <- data.frame(
  year = factor(sample(c("2019", "2020"), 100, replace = TRUE)),
  sv_weight = (sample(1:150, 100, replace = TRUE)),
  sex = factor(sample(c("Male", "Female"), 100, replace = TRUE)),
  race =  factor(sample(c("White", "Hispanic", "Black"), 100, replace = TRUE)))

library(table1)
tab<- table1(~ sex + race | year, data = dat) 

tab

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

日记撕了你也走了 2025-02-01 22:30:16

您可以使用调查gtsummary软件包的组合。 sumage :: svydesign中有一个选项以增加权重。然后,将调查对象将其管道输送到tbl_svysummary中。但是,根据您的预期输出,您可能需要使用不同的统计量或调整其他一些设置。

library(gtsummary)
library(dplyr)

results <-
  survey::svydesign(~ 1, data = dat, weights = ~ sv_weight) %>%
  tbl_svysummary(
    by = year,
    include = c(sex, race),
    statistic = list(all_categorical() ~ "{n_unweighted} ({p}%)")
  )

output

”在此处输入图像说明”

You can use a combination of the survey and gtsummary packages. There is an option in survey::svydesign to add weights. Then, the survey object is piped into tbl_svysummary. However, depending on your expected output, you might need to use a different statistic or adjust some of the other settings.

library(gtsummary)
library(dplyr)

results <-
  survey::svydesign(~ 1, data = dat, weights = ~ sv_weight) %>%
  tbl_svysummary(
    by = year,
    include = c(sex, race),
    statistic = list(all_categorical() ~ "{n_unweighted} ({p}%)")
  )

Output

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文