You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RunMean与mutate函数时出现评估错误的技术咨询

Fixing the Rolling Mean Calculation Error in R

First, let's address the most likely cause of your evaluation error: capitalization of the function name. You mentioned using RunMean in your problem description, but the correct function from the TTR package is runMean (lowercase 'r'). Using the capitalized version would throw an "object not found" error since that function doesn't exist in the package.

Assuming you fix that typo, let's also improve your code to be more efficient and idiomatic to dplyr (no need for a clunky loop!). Here's how to compute grouped rolling means directly with group_by and mutate:

install.packages('TTR')
library(dplyr)
library(TTR)

# Your original dataset
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)
)

# Compute grouped rolling mean without a loop
all_data <- df %>%
  group_by(name) %>%
  mutate(last3avg = runMean(amount, n = 3, cumulative = FALSE)) %>%
  ungroup() %>%
  arrange(index)

# View the final result
all_data

Key Notes:

  • Using group_by(name) tells dplyr to run the mutate operation separately for each unique name, which replaces your loop entirely. This is faster, cleaner, and easier to maintain.
  • When cumulative = FALSE, runMean returns NA for the first 2 observations in each group (since you need 3 data points to calculate the mean). For groups with fewer than 3 observations (like "D" in your data), all values will be NA—this is expected behavior.
  • Don't forget to ungroup() after the operation if you don't want the dataset to remain grouped by name.

This code should resolve your evaluation error and produce the grouped rolling means you're looking for.

内容的提问来源于stack exchange,提问作者Simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:07:18