我正在尝试计算滚动马哈拉诺比斯距离而不诉诸 for 循环并且惨遭失败。
这是一个示例数据集:
df <- data.frame(label = c(rep("A", 5), rep("B", 5)),
date = rep(seq.Date(from = as.Date("2018-01-01"), by = "days", length.out = 5), 2),
valx = c(rnorm(5, mean = 0, sd = 1), rnorm(5, mean = 1.5, sd = 1)),
valy = c(rnorm(5, mean = 100, sd = 10), rnorm(5, mean = 115, sd = 10)),
valz = c(rnorm(5, mean = 0, sd = 10), rnorm(5, mean = 0, sd = 30)))
我正在尝试按组 ( ) 计算 、和label
的马氏距离valx
,但仅使用该日期 ( ) 或之前的行。我目前的解决方案是遍历 each ,遍历 each ,将数据集过滤到匹配数据,使用 计算距离,将该距离添加到列表中,然后将它们放在循环之外*。显然这并不理想。valy
valz
date
label
date
stats::mahalanobis
do.call
rbind
我怀疑有一些方法可以写:
cum.mdist <- function(df, cols) {...}
df %>%
group_by(label) %>%
arrange(date) %>%
mutate(mdist = xapply(., c(valx, valy, valz), cum.mdist)) %>%
ungroup()
以类似于计算滚动一元函数的方式,如下所示:
cumsd <- function(x) sapply(seq_along(x), function(k, z) sd(z[1:k]), z = x)
如果没有协方差,我可以计算与组件的距离(滚动方差方差很容易使用上述函数计算),但我认为我的变量确实具有协方差,我不确定如何构建滚动协方差矩阵...
在 for 循环之外是否存在解决方案?
*循环解决方案的代码如下:
library("tidyverse")
df <- data.frame(label = c(rep("A", 5), rep("B", 5)),
date = rep(seq.Date(from = as.Date("2018-01-01"), by = "days", length.out = 5), 2),
valx = c(rnorm(5, mean = 0, sd = 1), rnorm(5, mean = 1.5, sd = 1)),
valy = c(rnorm(5, mean = 100, sd = 10), rnorm(5, mean = 115, sd = 10)),
valz = c(rnorm(5, mean = 0, sd = 10), rnorm(5, mean = 0, sd = 30)))
mdist.list <- vector(length = nrow(df), mode = "list")
counter <- 1
for(l in seq_along(unique(df$label))){
label_data <- df %>%
filter(label == unique(df$label)[l])
for(d in seq_along(unique(label_data$date))){
label_date_data <- label_data %>%
filter(date <= unique(label_data$date)[d])
if(nrow(label_date_data) > 3){
label_date_data$mdist <- mahalanobis(label_date_data %>% select(contains("val")),
colMeans(label_date_data %>% select(contains("val"))),
cov(label_date_data %>% select(contains("val"))))
} else{
label_date_data$mdist <- NA
}
mdist.list[[counter]] <- filter(label_date_data,
date == unique(label_data$date)[d])
counter <- counter + 1
}
}
mdist.df <- do.call(rbind, mdist.list)