【发布时间】:2020-12-19 14:59:21
【问题描述】:
我有一个数据框,其中包含一个名为 Product 的列(包含许多产品)、一个名为 Timestamp 的列(表示离散序数变量中的日期)和一个名为 Rating 的列。
我正在尝试计算每个产品的 Rating 变量的移动平均值和移动标准偏差,同时考虑时间戳。
数据看起来像这样:
DF <- data.frame(Product=c("a","a","a","a","b","b","b","c","c","c","c","c"),
Timestamp=c(1,2,3,4,1,2,3,1,2,3,4,5),
Rating=c(4,3,5,3,3,4,5,3,1,1,2,5))
现在我添加移动平均值和移动标准差的列:
DF$Moving.avg <- rep(0,nrow(DF))
DF$Moving.sd <- rep(0,nrow(DF))
最后,我将这段代码与嵌套的 for 循环一起使用以获得我想要的结果:
for (product in unique(DF$Product)) {
for (timestamp in DF[DF$Product==product,]$Timestamp){
if (timestamp==1) {
DF[DF$Product==product &
DF$Timestamp==timestamp,]$Moving.avg <-
DF[DF$Product==product &
DF$Timestamp==timestamp,]$Rating
DF[DF$Product==product &
DF$Timestamp==timestamp,]$Moving.sd <- 0
}else{
index_start <- which(DF$Product==product &
DF$Timestamp==1)
index_end <- which(DF$Product==product &
DF$Timestamp==timestamp)
DF[DF$Product==product &
DF$Timestamp==timestamp,]$Moving.avg <-
mean(DF[index_start:index_end,]$Rating)
DF[DF$Product==product &
DF$Timestamp==timestamp,]$Moving.sd <-
sd(DF[index_start:index_end,]$Rating)
}
}
}
代码运行良好,但速度太慢。 我想知道如何使用矢量化来加快速度?
【问题讨论】:
标签: r loops vectorization