如何在R中观察次数不同的情况下,重新计算单个和平均值混合的平均值? [英] How can I recalculate the mean of a mixture of individual and mean values with varying numbers of observations in R?

查看:71
本文介绍了如何在R中观察次数不同的情况下,重新计算单个和平均值混合的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两组正在使用的数据.第一个数据集是我从中获取测量值的一组单个标本,另一个数据集是先前研究中针对给定物种种群的一组报告的均值测量值.第一个数据集如下所示:

I have two sets of data I am working with. The first dataset is a set of individual specimens I have taken measurements from, and the other is a set of reported mean measurements for a given population of a species in previous studies. The first dataset looks like this:

data.frame(Species = c('Species1', "Species1", 'Species1', 'Species2', 'Species3', 'Species3'),
           Specimen = c('A1', 'B2', 'C3', 'D4', 'E5', 'F6'),
           Measurement1 = c(100, 110, 120, 130, 140,150),
           Measurement2 = c(1, 2, 3, 4, 5, 6))

,另一个看起来像这样:

and the other looks like this:

data.frame(Species = c('Species1','Species1', 'Species2', 'Species3'),
                  N = c(10, 10, 11, 12),
                  Measurement1 = c(100, 100, 110, 120),
                  Measurement2 = c(1, 2, 3, 4))

我想要做的是找到一种有效的方法来重新计算给定物种的平均值,给定该物种的所有观察结果.在上面给出的示例中,结果看起来像这样:

What I am trying to do is find an efficient way to recalculate the average value for a given species given all of the observations for that species. In the case of the example given above, the results would look something like this:

data.frame(Species=c('Species1','Species2','Species3'),
                  N=c(23,12,14),
                  Measurement1=c(101.3043,111.67,123.5714),
                  Measurement2=c(1.565,3,4.214))

我知道 aggregate()将计算给定数据帧的平均值,但是我不知道重新计算几个求和平均值的平均值的简便方法,或者如何做如果条目数变化,则为0.我知道可以使用公式手动重新计算平均值

I know aggregate() will calculate the mean value for a given data frame, but I don't know of any easy way to recalculate the mean of several summed mean values, or how to do it if the number of entries varies. I know the mean can be recalculated by hand using the formula

(Xx*Nx)+(Xy*Ny)+(X c * N c )/(N x + N y + N c )

(Xx*Nx)+(Xy*Ny)+(Xc*Nc) /(Nx+Ny+Nc)

但是我不知道如何用R编写这样一种方式,使得它可以使用由分组因子指定的不同数量的条目来完成.

but I don't know how to write it in R in such a way that it can be done with varying numbers of entries specified by a grouping factor.

推荐答案

您可以合并两个数据集,然后采用加权均值:

You can combine the two datasets and then take the weighted mean :

library(dplyr)

data1 %>%
  mutate(N = 1) %>%
  select(-Specimen) %>%
  bind_rows(data2) %>%
  group_by(Species) %>%
  summarise(across(starts_with('Measurement'), weighted.mean, N), 
            N = sum(N))

#  Species  Measurement1 Measurement2     N
#  <chr>           <dbl>        <dbl> <dbl>
#1 Species1         101.         1.57    23
#2 Species2         112.         3.08    12
#3 Species3         124.         4.21    14

这篇关于如何在R中观察次数不同的情况下,重新计算单个和平均值混合的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆