In R , is there any available function like IFERROR formula in EXCEL ? I want to calculate moving average using 4 nearest figures, but if the figures less than 4 in the group then using normal average. Detail refer to below code, the IF_ERROR is just i wished function and can't work
library(tidyverse)
library(TTR)
test_data <- data.frame(category=c('a','a','a','b','b','b','b','b','b'),
amount=c(1,2,3,4,5,6,7,8,9))
test_data %>% group_by(category) %>% mutate(avg_amount=IF_ERROR(TTR::runMedian(amount,4),
median(amount),
TTR::runMedian(amount,4))
In general, input should only generate errors in exceptional circumstances. It can be computationally expensive to catch and handle errors where a simple
ifstatement will suffice. The key here is realising thatrunMedianthrows an error if the group size is less than 4. Remember we can check the group size insidemutateby usingn(), so all you need do is:Additionally, if you want to replace the NA values from the beginning of the running median, you could use
ifelse: