我们拥有150个啤酒品牌的大型数据集,在399周内在85家商店销售。这些品牌仍被划分为子品牌(f.ex.:brand = Budweiser,但子品牌仍然存在:百威轻型/普通百威等)。我们想要创建一个功能,创建一个新的专栏,给我们每个品牌的平均价格,如果-品牌是一样的,-一周是一样的,-商店是一样的。
因此,我们的目标是得到一个列,显示每个品牌每周平均价格一家商店(f.ex.:百威在商店1在第一周)。我们很难创建这个if语句/循环,因为我们对R非常陌生。
到目前为止,我们已经尝试解决这个步骤,通过了解它将如何工作,没有一个循环。因此,我们选择了特定的商店、品牌和周,并创建了一个向量。像这样,我们可以创建向量mean_price,它将所有子品牌每周的所有价格相加,然后除以子品牌的数量(通过对子品牌向量的求和来计算)。
try1 <- subset(beer, select = c("brand","week","store","price_ounce","logprice_ounce", "sales_ounce","logsales_ounce"))
try1$vector <- c(1)
store5 <- subset(try1, store==5 & week==224 & brand=="ariel")
mean_price <- (sum(store5$logprice_ounce)/(sum(store5$vector)))
View(mean_price)
``
So far this leads to only one mean price, but we would like to have a column that displays 1 mean price per brand & store & week.
In the end, we need this to perform a regression to estimate price elasticities per store.
We are looking forward to any kind of help as we are completely lost.
Thank you in advance!发布于 2019-05-13 10:27:59
Dplyr库非常适合这种类型的分析。您可以在dplyr中达到每家商店/品牌/啤酒的平均水平:
library(dplyr)
brand <- c("bud", "bud", "bud")
week <- c(1,1,1)
store <- c("A", "A", "A")
price_ounce <- c(2,3,2.2)
data <- data.frame(brand, week, store, price_ounce) %>%
mutate(logprice_ounce = log(price_ounce))
answer <- data %>%
group_by(brand, week, store) %>%
summarise(meanPrice = mean(price_ounce),
geomMeanPrice = exp(mean(logprice_ounce)))你可能会发现这本书很有用:R数据科学
发布于 2019-05-13 10:34:49
实际上,你不需要任何循环来做你想做的事情。例如,您可以使用库data.table。
library(data.table)
beer[, Mean:=mean(price_ounce), by=list(brand,week,store)]您可以使用另一个名为dplyr的库来完成此操作,但我鼓励您查看data.table,它在处理大型数据集时速度更快。
我希望它能帮到你。
https://stackoverflow.com/questions/56110120
复制相似问题