按天计算平均价格

时间:2020-01-18 19:19:03

标签: r dataframe dplyr mean

我猜这是一个简单的任务... 我正在尝试计算每天的平均价格。这里有3个不同的日子,每个日子都有一些价格。 这是我最初拥有的DataFrame

 ID       Date      RoomAv    Price
  1    2001-01-02    TRUE      110
  2    2001-01-04    FALSE     120
  3    2001-01-03    TRUE      130
  4    2001-01-03    TRUE      140
  5    2001-01-03    TRUE      150
  6    2001-01-02    FALSE     160
  7    2001-01-02    TRUE      170
  8    2001-01-04    TRUE      180
  9    2001-01-04    FALSE     190
 10    2001-01-02    TRUE      200

我需要像这样

    Date      AveragePrice
 2001-01-02       num1
 2001-01-03       num2
 2001-01-04       num3

这就是我试图做的

df <- DataFrame %>%
  group_by(DataFrame$Date) %>%
  summarize(DataFrame$price == mean(DataFrame$Price))

然后我得到了

Error: Column `DataFrame$price == mean(DataFrame$Price)` must be length 1 (a summary value), not 0

尚未使用data.table库,但想听听那里的可能性。

5 个答案:

答案 0 :(得分:4)

带有data.table

的选项
library(data.table)
setDT(df)[, .(Price = mean(Price), by = Date]

答案 1 :(得分:2)

您可以做类似的事情

使用dplyr

insert into TRACK (<TRACK>)

使用data.table

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    val view = holder.itemView
    val favoriteData = DatabaseHelper(view.context).loadFavoriteData() 
    val favorite = favoriteData.find { data.results[position].id.toString() == it.id }
    view.toggle_favorite.isChecked = (favorite != null)

}

答案 2 :(得分:2)

您可以从底数R中使用aggregate()来实现:

dfout <- aggregate(Price ~Date, df, mean)

这样

> dfout
        Date    Price
1 2001-01-02 160.0000
2 2001-01-03 140.0000
3 2001-01-04 163.3333

数据

df <- structure(list(ID = 1:10, Date = c("2001-01-02", "2001-01-04", 
"2001-01-03", "2001-01-03", "2001-01-03", "2001-01-02", "2001-01-02", 
"2001-01-04", "2001-01-04", "2001-01-02"), RoomAv = c(TRUE, FALSE, 
TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE), Price = c(110L, 
120L, 130L, 140L, 150L, 160L, 170L, 180L, 190L, 200L)), class = "data.frame", row.names = c(NA, 
-10L))

答案 3 :(得分:1)

请记住,R中的==用于测试某个值是否等于另一个值,例如x == 1。因此,您应该在摘要中使用=分配新变量。这是正确的版本。

library(dplyr)
DataFrame %>%
  group_by(Date) %>%
  summarize(avrgPrice = mean(Price))

答案 4 :(得分:0)

谢谢, 其实我发现这种方法最短:

import itertools

result = list(itertools.chain(*original_list))