使用RunMean与mutate函数时出现评估错误的技术咨询
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 themutateoperation separately for each unique name, which replaces your loop entirely. This is faster, cleaner, and easier to maintain. - When
cumulative = FALSE,runMeanreturnsNAfor 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 beNA—this is expected behavior. - Don't forget to
ungroup()after the operation if you don't want the dataset to remain grouped byname.
This code should resolve your evaluation error and produce the grouped rolling means you're looking for.
内容的提问来源于stack exchange,提问作者Simon

