计算一个变量的加权平均值,该变量具有两种类型的r

发布于 2025-02-10 17:23:20 字数 571 浏览 2 评论 0原文

我有以下数据集,其中次数(“ n”)变量“ v0220”出现在“ id_municipio”的数据中,但是该变量有两种类型:1和2。 ”)每个观察结果。

id_municipio peso_amostral v0220     n
     1100015          2.04     2     1
     1100015          2.68     1     1
     1100015          3.45     2     1
     1100015          4.51     1     1
     1100015          4.62     2     1
     1100015          4.75     1     1

我想做的是以下内容:

id_municipio  2     1
   1100015    X     Y

因此,我想计算ID_Municipio的此变量类型(2或1)的每个变量“ V0220”的加权均值。请注意,“ x”和“ y”分别是按2和1分别按“ V0220”的加权平均值。我想使用R进行。

I have the following dataset with the number of times ("n") the variable "V0220" appears in the data by the "id_municipio", but this variable has two types: 1 and 2. Moreover, I have the weight ("peso_amostral") of each observation.

id_municipio peso_amostral v0220     n
     1100015          2.04     2     1
     1100015          2.68     1     1
     1100015          3.45     2     1
     1100015          4.51     1     1
     1100015          4.62     2     1
     1100015          4.75     1     1

What I would like to do is the following:

id_municipio  2     1
   1100015    X     Y

Therefore, I want to calculate the weighted mean for each variable "V0220" for the type (2 or 1) of this variable by id_municipio. Note that "X" and "Y" are the weighted mean values for "V0220", by type 2 and 1, respectively. I want to do it using R.

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

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

发布评论

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

评论(1

旧竹 2025-02-17 17:23:20

您可以使用dcastdata.table尝试此操作。您可以为所需功能更改fun.ggregate

library(data.table)

dcast(data, 
      id_municipio ~ v0220, 
      fun.aggregate = mean, 
      value.var     = "peso_amostral")

输出:

  id_municipio    1    2
1      1100015 3.98 3.37

You can try this using dcast from data.table. You can change fun.aggregate for the function that you need.

library(data.table)

dcast(data, 
      id_municipio ~ v0220, 
      fun.aggregate = mean, 
      value.var     = "peso_amostral")

OUTPUT:

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