计算均值,但留下唯一变量的数量

Calculating a mean, but leaving numbers of unique variables

我在使用 R 和 plyr 时遇到了一些困难,我不知道如何获得我感兴趣的结果。我有一个如下所示的数据框:

Region Price
Alentejano 71
Andalucia 30
Bordeaux 135
Bordeaux 500
Bordeaux 185

等等。我想获得每个区域的平均值,到目前为止,我尝试使用 plyr 和代码:

means <- ddply(data, ~ Region, summarise, mean = mean(Price), sd=sd(Price))

在每个变量有多个观察值的地方,它成功地给出了标准偏差。我没有任何办法。我如何制作一个代码,为我提供多个纪念日的平均值,但如果只有一个纪念日,则保留数字?

这将为您提供所需的答案

means <- ddply(data, ~ Region, summarise, mean = mean(Price[duplicated(Price)]), sd=sd(Price))

根据您的代码,您使用的不是 dplyr,而是 plyr。当您取一次观察的平均值时,它将 return 该观察的值:

关于您的示例数据:

aggregate(Price ~ Region, dat, FUN = mean)

returns:

      Region    Price
1 Alentejano  71.0000
2  Andalucia  30.0000
3   Bordeaux 273.3333

如您所见,"Alentejano" 和 "Andalucia" 区域 return 编辑了与原始数据中相同的值。

使用您提供的代码:

library(plyr)
ddply(dat, ~ Region, summarise, mean = mean(Price), sd=sd(Price))

我得到:

      Region     mean       sd
1 Alentejano  71.0000       NA
2  Andalucia  30.0000       NA
3   Bordeaux 273.3333 197.8846

这是预期的有效结果。

如果您同时使用 plyrdplyr,请确保您在 dplyr 之前加载了 plyr。否则您将收到以下警告消息:

------------------------------------------------------------------------------------
You have loaded plyr after dplyr - this is likely to cause problems.
If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
library(plyr); library(dplyr)
------------------------------------------------------------------------------------

已用数据:

dat <- read.table(text="Region Price
Alentejano 71
Andalucia 30
Bordeaux 135
Bordeaux 500
Bordeaux 185", header=TRUE)