面对问题,根据子类别获得准确的比例

发布于 01-15 01:39 字数 256 浏览 3 评论 0原文

在此处输入图像描述

这是我的数据。每年我都想获得每个 marital_status 的比例。例如,2000年已婚人口比例为57291/(57291+58238+18181)。像这样,对于每年和每个 marital_case 我想要一个比例。但在 R 中,当我做比例时,marital_status 的所有计数都被添加,它给出了整个数据帧的比例。我尝试过 group_by 但不起作用。

enter image description here

This is my data. For each year I want to get the proportion of each of marital_status. For instance, in the year 2000 proportion of married people is 57291/(57291+58238+18181). Like this, for each year and for each marital_case I want a proportion. But in R, when I am doing proportion, all the counts of marital_status are added and it gives a proportion of the whole data frame. I have tried group_by but doesn't work.

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

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

发布评论

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

评论(1

最舍不得你2025-01-22 01:39:54

下次尝试制作一个reprex(即最小的可重现示例)。

这里是一个最小的数据表示例:

year <- c(2000, 2000, 2000, 2010, 2010, 2010)
marital_status <- c("married", "never-married", "sep-div-wid", "married", "never-married", "sep-div-wid")
n <- c(1254, 1000, 550, 1532, 1258, 450)

dataframe <- data.frame(year, marital_status, n)

要计算每年的比例,只需 group_by() 年:

dataframe %>%
  group_by(year) %>%
  mutate(prop = n / sum(n))

Next time try and make a reprex (i.e. minimal reproducible example).

A minimal data table example here:

year <- c(2000, 2000, 2000, 2010, 2010, 2010)
marital_status <- c("married", "never-married", "sep-div-wid", "married", "never-married", "sep-div-wid")
n <- c(1254, 1000, 550, 1532, 1258, 450)

dataframe <- data.frame(year, marital_status, n)

To calculate proportion per year simply group_by() year:

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