这是我的代码:
install.packages('TTR')
library(dplyr)
library(TTR)
df <- data.frame(index = 1:20, name = c("A", "B", "C", "A", "A", "C", "B", "C", "A", "B", "C", "A", "A", "A", "C", "B", "C", "A", "B", "D"), amount = c(10,14,3,4,15,9,12,6,7,8,10,13,12,6,8,8,9,3,14,10))
all_data=data.frame()
for (a in unique(df$name)){
data=df%>%filter(name==a)%>%mutate(last3avg=runMean(amount, n = 3, cumulative = FALSE))
all_data=rbind(data,all_data)
}
all_data=all_data%>%arrange(index)
这就是错误:
mutate_impl(.data,dots)中的错误: 评估错误:n = 3超出有效范围:[1,1]。
为什么会发生此错误以及如何解决?
答案 0 :(得分:0)
尝试运行:
runMean(df %>% filter(name == "A") %>% select(amount), n = 3, cumulative = FALSE)
现在,试试这个:
runMean(df %>% filter(name == "D") %>% select(amount), n = 3, cumulative = FALSE)
区别在于D
只有一个条目,因此n = 3
毫无意义。
编辑以解决以下评论
为避免错误,您可以进行过滤以确保每个name
始终至少有3个实例。例如,
df %<>% group_by(name) %>% filter(n() >= 3) %>% ungroup